src/Controller/Admin/DashboardController.php line 5018

  1. <?php
  2. namespace App\Controller\Admin;
  3. use EasyCorp\Bundle\EasyAdminBundle\Config\Dashboard;
  4. use EasyCorp\Bundle\EasyAdminBundle\Config\MenuItem;
  5. use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractDashboardController;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Annotation\Route;
  8. use Aws\S3\S3Client;
  9. use Symfony\Component\Uid\Uuid;
  10. use Doctrine\Persistence\ManagerRegistry;
  11. use Symfony\Component\HttpFoundation\Request;
  12. use App\Entity\Caixa;
  13. use App\Entity\Documento;
  14. use App\Entity\Tipo;
  15. use App\Entity\Classificacao;
  16. use App\Entity\Cliente;
  17. use App\Entity\User;
  18. use App\Entity\Cx;
  19. use App\Entity\ClienteAll;
  20. use App\Entity\Registro;
  21. use App\Entity\Fluxo;
  22. use App\Entity\Etapa;
  23. use App\Entity\MessengerMessages;
  24. use Doctrine\ORM\EntityManagerInterface;
  25. use setasign\Fpdi\Tcpdf\Fpdi;
  26. use setasign\Fpdi\PdfReader;
  27. use propa\tcpdi\tcpdi;
  28. use Symfony\Component\Dotenv\Dotenv;
  29. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  30. use Symfony\Component\String\Slugger\AsciiSlugger;
  31. use App\Form\UploadType;
  32. use PhpOffice\PhpSpreadsheet\IOFactory;
  33. use Symfony\Component\Mime\Email;
  34. use Symfony\Component\Mailer\MailerInterface;
  35. use Knp\Component\Pager\PaginatorInterface;
  36. use Dompdf\Dompdf;
  37. use Dompdf\Options;
  38. use Endroid\QrCode\Builder\Builder;
  39. use Endroid\QrCode\Encoding\Encoding;
  40. use Twig\Environment;
  41. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  42. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  43. use PhpOffice\PhpSpreadsheet\Shared\Date;
  44. use PhpOffice\PhpSpreadsheet\Style\Color;
  45. use PhpOffice\PhpSpreadsheet\Style\Fill;
  46. use Endroid\QrCode\ErrorCorrectionLevel\ErrorCorrectionLevelHigh;
  47. use Endroid\QrCode\Writer\PngWriter;
  48. use App\Message\UploadMultipartMessage;
  49. use Symfony\Component\Messenger\MessageBusInterface;
  50. use Symfony\Component\HttpFoundation\JsonResponse
  51. use DateTime;
  52. class DashboardController extends AbstractDashboardController
  53. {
  54.     
  55.     #[Route('/'name'inicial')]
  56.     public function home(): Response
  57.     {
  58.         
  59.         return $this->redirectToRoute('home');
  60.     }
  61.     
  62.     #[Route('/login_sucess'name'login_sucess')]
  63.     public function login_sucess(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManager): Response
  64.     {
  65.         
  66.     
  67.         $user_logado $this->getUser();
  68.         $enabled $user_logado->getEnabled();
  69.         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  70.             $ip_cliente explode(','$_SERVER['HTTP_X_FORWARDED_FOR'])[0];
  71.         } else {
  72.             $ip_cliente $_SERVER['REMOTE_ADDR'];
  73.         }
  74.         
  75.           if($enabled == false){
  76.             $error ="Tentativa de login de usuário desativado";
  77.             $user_logado_nome=$user_logado->getNome();
  78.             $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  79.             $registro = new Registro();
  80.             $registro->setOperacao($error);
  81.             $registro->setUser($user_logado_nome);
  82.             $registro->setData($hoje);
  83.             $registro->setIp($ip_cliente);
  84.             $entityManager->persist($registro);
  85.             $entityManager->flush();
  86.             return $this->redirectToRoute('app_logout');
  87.         }
  88.         
  89.         
  90.         
  91.         
  92.         $error ="Login Realizado";
  93.         $user_logado_nome=$user_logado->getNome();
  94.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  95.         $registro = new Registro();
  96.         $registro->setOperacao($error);
  97.         $registro->setUser($user_logado_nome);
  98.         $registro->setData($hoje);
  99.         $registro->setIp($ip_cliente);
  100.         $entityManager->persist($registro);
  101.         $entityManager->flush();
  102.         
  103.       
  104.         
  105.         
  106.         
  107.         
  108.         
  109.         return $this->redirectToRoute('home');     
  110.     }
  111.     
  112.     #[Route('/index/home'name'home')]
  113.     public function inicial(PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer): Response
  114.     {
  115.         $user_logado $this->getUser();
  116.         $user_logado_id $user_logado->getId();
  117.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  118.         $erro '';
  119.         $pagina 'home';
  120.         $p ='';
  121.         
  122.         $etapas  null;
  123.         if(isset($_POST["btn_cliente"])){
  124.             
  125.             $session->set('cliente_id'$_POST["btn_cliente"]);
  126.             return $this->redirectToRoute('home');
  127.         }
  128.         
  129.         $clienteId $session->get('cliente_id');
  130.         
  131.         $etapas $doctrine->getRepository(Etapa::class)->findByUserAndUpdatedAt($user_logado);
  132.         
  133.        
  134.         return $this->render('index/index6.html.twig', [
  135.     
  136.             
  137.             'p'=>$p,
  138.             'erro'=>$erro,
  139.             'pagina' => $pagina,
  140.             'etapas'=>$etapas,
  141.             'cliente' => $cliente,
  142.             'clienteId' => $clienteId
  143.             
  144.             
  145.         ]);
  146.     } 
  147.     #[Route('/index/troca'name'troca')]
  148.     public function troca(SessionInterface $session): Response
  149.     {
  150.        
  151.         $session->remove('cliente_id');
  152.         $session->invalidate();
  153.         return $this->redirectToRoute('home');
  154.     }
  155.     #[Route('/index/export'name'export')]
  156.     public function export(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $session,MessageBusInterface $bus): Response
  157.     {
  158.         
  159.         
  160.         $pendingMessages $entityManager->getRepository(MessengerMessages::class)->countPendingMessages();
  161.         
  162.         #dd($pendingMessages);
  163.         
  164.         $user_logado $this->getUser();
  165.         $user_logado_id $user_logado->getId();
  166.         $userId $user_logado_id;
  167.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  168.         $dotenv = new Dotenv();
  169.         $dotenv->load(__DIR__.'/.env');
  170.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  171.         $hoje_formt=$hoje->format('Y-m-d') ;
  172.         $doc $entityManager->getRepository(Documento::class)->findByUserAndDate($user_logado_id$hoje_formt);
  173.         $dia_prod 'de hoje';
  174.         
  175.    
  176.         if(isset($_POST["date_perio"])){
  177.             
  178.             
  179.             $startDate $_POST["de"];
  180.             $endDate $_POST["ate"];
  181.        
  182.             $de = new \DateTimeImmutable($startDate);
  183.             $ate = new \DateTimeImmutable($endDate);
  184.             $de_formt=$de->format('d/m/Y') ;
  185.             $ate_formt=$ate->format('d/m/Y') ;
  186.             
  187.             if($endDate != ""){ 
  188.                 
  189.                 $doc $entityManager->getRepository(Documento::class)->findByUserAndDateRange($user_logado_id$startDate$endDate);
  190.                 $dia_prod 'de '$de_formt.' até '.$ate_formt
  191.             
  192.             }
  193.             if($endDate == ""){ 
  194.                 
  195.                 $doc $entityManager->getRepository(Documento::class)->findByUserAndDate($user_logado_id$startDate);
  196.                 $dia_prod 'de '$de_formt
  197.             }
  198.             
  199.             
  200.         }
  201.         
  202.         if(isset($_POST["btn_cliente"])){
  203.             
  204.             $session->set('cliente_id'$_POST["btn_cliente"]);
  205.             return $this->redirectToRoute('home');
  206.         }
  207.         $clienteId $session->get('cliente_id');
  208.         
  209.         
  210.         
  211.         if ($clienteId == null ) {
  212.             
  213.             $caixas =  "";
  214.             $index_all ="";
  215.             $documentos="";
  216.             $cliente_session "";
  217.             $cliente_alls "";
  218.        
  219.         } else {
  220.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  221.             $caixas $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  222.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  223.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  224.             $cliente_alls $cliente_session->getClienteAll()->getId();
  225.         }
  226.         $erro '';
  227.         $ii=0;
  228.         $pagina 'export';
  229.         $p '';
  230.         $link '';
  231.         $mx 0;
  232.         $xy 
  233.         $yz 
  234.         $ay ;
  235.         $ky ;
  236.         $pdf ='';
  237.         $pagina_h4 ='Documento(s) para indexar';
  238.         $nome_menu_ '';
  239.         $index_tipo='';
  240.         
  241.         $user $this->getUser();
  242.         $user_nome$user->getEmail();
  243.         $user_nome_name$user->getNome();
  244.         $pasta_user=$user_nome.'/';
  245.         $arr = [];
  246.         $arrr=0;
  247.         $index_find null;
  248.         $dt '';
  249.         $clientS3 = new  S3Client([
  250.             'region'  => 'sa-east-1',
  251.             'version' => 'latest',
  252.             'credentials' => [ 
  253.                 'key'    => $_ENV['AWS_KEY'],
  254.                 'secret' => $_ENV['AWS_SECRET'],
  255.             ],
  256.         ]);
  257.         
  258.        if (isset($_POST["botao_export"])) {
  259.             $caixaId $_POST["caixas"];
  260.             $caixa_id $doctrine->getRepository(Caixa::class)->find($_POST["caixas"]);
  261.             $cliente_id $doctrine->getRepository(Cliente::class)->find($clienteId);
  262.             $clientes_status$cliente_id->getExtraFields();
  263.             if(!$clientes_status){
  264.                 $clientes_status="ged";
  265.             }
  266.             $cliente_nome $cliente_id->getNome();
  267.             $clientes $cliente_id->getId();
  268.             $conteiner $_POST["conteiner"];
  269.             $cont_file 0;
  270.             $umlautString $cliente_nome;
  271.             $slugger = new AsciiSlugger();
  272.             $teste $slugger->slug($umlautString$seperator '-')->toString();
  273.             $caminho strtolower($teste '/');
  274.             if ($clientes == 14) { $caminho 'cartorio-1deg-oficio-de-volta-redonda-rj/'; }
  275.             if ($clientes == 83) { $caminho 'casf-corretora-apolice-diversos/'; }
  276.             if ($clientes == 35) { $caminho 'pmecj-sp-saude/'; }
  277.             if ($clientes == 107) { $caminho 'pmecj-sp-execucao-fiscal/'; }
  278.             if ($clientes == 4) { $caminho 'cartorio-souza-reis-barra-mansa/'; }
  279.             if ($clientes == 112) { $caminho 'saae-cartao-de-ponto/'; }
  280.             if ($clientes == 15) { $caminho 'cbsi-dossies/'; }
  281.             if ($clientes == 55) { $caminho 'casf-gerep-contratos-de-prestadores-de-saude-pj/'; }
  282.             if ($clientes == 13) { $caminho 'casa-de-saude-santa-maria-c-s-s.M/'; }
  283.             if ($clientes == 40) { $caminho 'fasf-atas-e-diarios/'; }
  284.         
  285.             $filesTmp  $_FILES['file']['tmp_name'];
  286.             $filesName $_FILES['file']['name'];
  287.             
  288.             foreach ($filesTmp as $index => $file) {
  289.             
  290.                 $uuid Uuid::v4();
  291.                 $cont_file++;
  292.                 
  293.                 
  294.                 // nome original do arquivo
  295.                 $originalName pathinfo($filesName[$index], PATHINFO_FILENAME);
  296.                 
  297.                 // sanitiza o nome (remove acentos, espaços estranhos etc.)
  298.                 $slugger = new AsciiSlugger();
  299.                 $safeName strtolower($slugger->slug($originalName)->toString());
  300.                 
  301.                 // 🔹 Se cliente for local, usa nome original
  302.                 if ($clientes_status === 'local') {
  303.             
  304.             
  305.                     $filename $safeName '.pdf';
  306.             
  307.                 } else {
  308.                     if ($cliente_alls === 42) {
  309.                          $filename $originalName '.pdf';
  310.                     }else{
  311.                         $filename $uuid '.pdf';
  312.                     }
  313.                 }
  314.             
  315.                 $tempDir __DIR__ '/../../var/uploads/messenger';
  316.                 if (!is_dir($tempDir)) {
  317.                     mkdir($tempDir0777true);
  318.                 }
  319.             
  320.                 $tempFilePath $tempDir '/' $filename;
  321.             
  322.                 move_uploaded_file($file$tempFilePath);
  323.                 chmod($tempFilePath0644);
  324.                 if (!file_exists($tempFilePath) || filesize($tempFilePath) === 0) {
  325.                     throw new \RuntimeException(
  326.                         'Falha ao gravar PDF temporário: ' $tempFilePath
  327.                     );
  328.                 }
  329.                 
  330.                 // evita race condition de filesystem
  331.                 clearstatcache(true$tempFilePath);
  332.                 
  333.                 $bus->dispatch(new UploadMultipartMessage(
  334.                     $tempFilePath,
  335.                     $filename,
  336.                     $caminho,
  337.                     '',
  338.                     $caixaId,
  339.                     $clienteId,
  340.                     $userId,
  341.                     0,
  342.                     $conteiner,
  343.                     $clientes,
  344.                     $clientes_status,
  345.                     $safeName,
  346.                     $originalName,
  347.                     $cliente_alls
  348.                 ));
  349.             }
  350.         
  351.             $log = new Registro();
  352.             $log->setOperacao('EXPORTOU ' $cont_file ' DOCUMENTO(S)');
  353.             $log->setUser($user_nome_name);
  354.             $log->setCliente($cliente_nome);
  355.             $entityManager->persist($log);
  356.             $entityManager->flush();
  357.         
  358.             return $this->redirectToRoute('export');
  359.         }
  360.       
  361.         return $this->render('index/index.html.twig', [
  362.             'documentos' => $documentos,
  363.             'xy' => $xy,
  364.             'yz' => $yz,
  365.             'ay'=>$ay,
  366.             'link' => $link,
  367.             'pdf'=>$pdf,
  368.             'p'=>$p,
  369.             'erro'=>$erro,
  370.             'index_all'=>$index_all,
  371.             'index_tipo'=>$index_tipo,
  372.             'ky'=>$ky,
  373.             'pagina' => $pagina,
  374.             'pagina_h4' =>$pagina_h4,
  375.             'index_find'=>$index_find,
  376.             'mx'=>$mx,
  377.             'caixas' => $caixas,
  378.             'user_logado' => $user_logado,
  379.             'cliente' => $cliente,
  380.             'cliente_session' => $cliente_session,
  381.             'doc'=>$doc,
  382.             'dia_prod' => $dia_prod
  383.         ]);
  384.     }
  385.     
  386.     #[Route('/index/planilha'name'planilha')]
  387.     public function planilha(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $session): Response
  388.     {
  389.         
  390.       
  391.         $form $this->createForm(UploadType::class);
  392.         $user_logado$this->getUser();
  393.         $user_logado_id $user_logado->getId();
  394.         $user_nome_name$user_logado->getNome();
  395.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  396.         $form->handleRequest($request);
  397.         $dotenv = new Dotenv();
  398.         $dotenv->load(__DIR__.'/.env');
  399.         $erro '';
  400.         $excel 0;
  401.         $pagina 'index';
  402.         $p '';
  403.         $clientS3 = new  S3Client([
  404.             'region'  => 'sa-east-1',
  405.             'version' => 'latest',
  406.             'credentials' => [ 
  407.                 'key'    => $_ENV['AWS_KEY'],
  408.                 'secret' => $_ENV['AWS_SECRET'],
  409.             ],
  410.         ]);
  411.    
  412.         
  413.         
  414.         if(isset($_POST["btn_cliente"])){
  415.             
  416.             $session->set('cliente_id'$_POST["btn_cliente"]);
  417.             return $this->redirectToRoute('home');
  418.         }
  419.         $clienteId $session->get('cliente_id');
  420.         
  421.         
  422.         
  423.         if ($clienteId == null ) {
  424.             
  425.             $caixas =  "";
  426.             $index_all ="";
  427.             $documentos="";
  428.             $cliente_session "";
  429.        
  430.         } else {
  431.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  432.             $caixas $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  433.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  434.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  435.             $cliente_nome$cliente_session->getNome();
  436.             
  437.         }
  438.         
  439.         
  440.        
  441.         
  442.       
  443.         if ($form->isSubmitted() && $form->isValid()) {
  444.             $list =[];
  445.             $file $form['file']->getData();
  446.             $spreadsheet IOFactory::load($file->getPathname());
  447.             $sheetData $spreadsheet->getActiveSheet()->toArray();
  448.             foreach ($sheetData as $row) {
  449.                 $excel ++;
  450.                 $id_cx null ;
  451.                 $selections $_POST["selections"];
  452.                 $nome array_search('0'$selections);
  453.                 $caixa array_search('1'$selections);
  454.                 $assunto array_search('2'$selections);
  455.                 $keywod array_search('3'$selections);
  456.                 $data_documento array_search('4'$selections);
  457.                 $data_vecimento array_search('5'$selections);
  458.                 $descricao  array_search('6'$selections);
  459.                 
  460.                 if ($caixa != false ) {
  461.                         
  462.                     
  463.                     $numerosExcel preg_replace('/\D/'''$row[$caixa]);
  464.                     foreach ($caixas as $key) {
  465.                         $nome_cx $key->getNome();
  466.                         $numerosCaixa preg_replace('/\D/'''$nome_cx);
  467.                         if ($numerosCaixa == $numerosExcel ) {
  468.                             
  469.                                 $id_cx $key->getId();
  470.                         }
  471.                     }
  472.                     
  473.                     
  474.                     if ($id_cx == null) {
  475.                         echo '<script>alert("ERRO NA LINHA '.$excel.' NÃO EXISTE ESSA CAIXA CADASTRADA")</script>';
  476.                             return $this->render('index/index2.html.twig', [
  477.                             'documentos' => $documentos,
  478.                             'p'=>$p,
  479.                             'erro'=>$erro,
  480.                             'index_all'=>$index_all,
  481.                             'pagina' => $pagina,
  482.                             'caixas' => $caixas,
  483.                             'user_logado' => $user_logado,
  484.                             'cliente' => $cliente,
  485.                             'cliente_session' => $cliente_session,
  486.                             'form' => $form->createView(),
  487.                                             ]);
  488.                     }
  489.                 }
  490.                 
  491.                 
  492.                     $yourEntity = new Documento();
  493.                     // Ajuste conforme necessário
  494.                     $yourEntity->setUser($user_logado);
  495.                     $yourEntity->setCliente($cliente_session);
  496.                     $yourEntity->setClassificacao($doctrine->getRepository(Classificacao::class)->find(1));
  497.                     $yourEntity->setTipo($doctrine->getRepository(Tipo::class)->find($_POST["tipo"]));
  498.                     $yourEntity->setNome($row[$nome]); 
  499.                     if ($assunto != false ) {$yourEntity->setAssunto($row[$assunto]);}
  500.                     if ($caixa != false ) {$yourEntity->setCaixa($doctrine->getRepository(Caixa::class)->find($id_cx));}
  501.                     if ($keywod != false ) {$yourEntity->setKeywords($row[$keywod]);}
  502.                     if (!empty(trim($row[$data_documento])) && strtoupper(trim($row[$data_documento])) !== "NULL") {
  503.                         $yourEntity->setDataDocumento(new \DateTimeImmutable($row[$data_documento]));
  504.                     }
  505.                     
  506.                     #if (!empty(trim($row[$data_vecimento])) && strtoupper(trim($row[$data_vecimento])) !== "NULL") {
  507.                      #   $yourEntity->setVencimentoDocumento(new \DateTimeImmutable($row[$data_vecimento]));
  508.                     #}
  509.                     if ($descricao != false ) {$yourEntity->setExtraFields($row[$descricao]);}
  510.                     $entityManager->persist($yourEntity);
  511.                     $entityManager->flush();
  512.                     $erro "ok";
  513.                     
  514.                    
  515.                     
  516.             }
  517.                 
  518.                 $log = new Registro();
  519.                 $log->setOperacao('PLANILHA EXPORTADA, '.$excel .' CADASTROS INSERIDOS.' ); 
  520.                 $log->setUser($user_nome_name);
  521.                 $log->setCliente($cliente_nome);
  522.                 $entityManager->persist($log);
  523.                 $entityManager->flush();
  524.                 $erro "ok";
  525.                 if ($excel>1)  {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTROS INSERIDOS , .' ;}
  526.                 if ($excel==1) {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTRO INSERIDO ,' ;}
  527.             
  528.         }
  529.         
  530.         return $this->render('index/index2.html.twig', [
  531.                             'documentos' => $documentos,
  532.                             'p'=>$p,
  533.                             'erro'=>$erro,
  534.                             'index_all'=>$index_all,
  535.                             'pagina' => $pagina,
  536.                             'caixas' => $caixas,
  537.                             'user_logado' => $user_logado,
  538.                             'cliente' => $cliente,
  539.                             'cliente_session' => $cliente_session,
  540.                             'form' => $form->createView(),
  541.                                             ]);
  542.        
  543.     }
  544.     
  545.     #[Route('/index/planilha/classificacao'name'planilha_classificacao')]
  546.     public function planilha_classificacao(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $session): Response
  547.     {
  548.         
  549.       
  550.         $form $this->createForm(UploadType::class);
  551.         $user_logado$this->getUser();
  552.         $user_logado_id $user_logado->getId();
  553.         $user_nome_name$user_logado->getNome();
  554.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  555.         $form->handleRequest($request);
  556.         $erro '';
  557.         $excel 0;
  558.         $pagina 'index';
  559.         $p '';
  560.         if(isset($_POST["btn_cliente"])){
  561.             
  562.             $session->set('cliente_id'$_POST["btn_cliente"]);
  563.             return $this->redirectToRoute('home');
  564.         }
  565.         $clienteId $session->get('cliente_id');
  566.         
  567.         
  568.         
  569.         if ($clienteId == null ) {
  570.             
  571.             $caixas =  "";
  572.             $cliente_session "";
  573.        
  574.         } else {
  575.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  576.             $cliente_nome$cliente_session->getNome();  
  577.         }
  578.         
  579.         
  580.        
  581.         
  582.       
  583.         if ($form->isSubmitted() && $form->isValid()) {
  584.             $list =[];
  585.             $file $form['file']->getData();
  586.             $spreadsheet IOFactory::load($file->getPathname());
  587.             $sheetData $spreadsheet->getActiveSheet()->toArray();
  588.             foreach ($sheetData as $row) {
  589.                 $excel ++;
  590.                 $id_cx null ;
  591.                 $selections $_POST["selections"];
  592.                 $nome array_search('0'$selections);
  593.                 $fase_corrente array_search('1'$selections);
  594.                 $fase_intermediaria array_search('2'$selections);
  595.                 $destinacao_final array_search('3'$selections);
  596.                 $observacoes array_search('4'$selections);
  597.                 $descricao array_search('5'$selections);
  598.                 
  599.                 
  600.                 if($row[$nome] != null){
  601.                 
  602.                     $yourEntity = new Classificacao();
  603.                     $yourEntity->setNome($row[$nome]);
  604.                     $yourEntity->setFaseCorrente($row[$fase_corrente]);
  605.                     $yourEntity->setFaseIntermediaria($row[$fase_intermediaria]);
  606.                     $yourEntity->setDestinacaoFinal($row[$destinacao_final]);
  607.                     $yourEntity->setObservacoes($row[$observacoes]);
  608.                     $yourEntity->setExtraFields($row[$descricao]);
  609.                     $yourEntity->setCliente($cliente_session);
  610.                     $entityManager->persist($yourEntity);
  611.                     $entityManager->flush();
  612.                     $erro "ok";
  613.                 }
  614.                
  615.                     
  616.                    
  617.                     
  618.             }
  619.                 
  620.             $log = new Registro();
  621.             $log->setOperacao('PLANILHA EXPORTADA, '.$excel .' CADASTROS INSERIDOS.' ); 
  622.             $log->setUser($user_nome_name);
  623.             $log->setCliente($cliente_nome);
  624.             $entityManager->persist($log);
  625.             $entityManager->flush();
  626.             $erro "ok";
  627.             if ($excel>1)  {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTROS INSERIDOS , .' ;}
  628.             if ($excel==1) {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTRO INSERIDO ,' ;}
  629.             
  630.         }
  631.         
  632.         return $this->render('index/index_classificao.html.twig', [
  633.                             'p'=>$p,
  634.                             'erro'=>$erro,
  635.                             'pagina' => $pagina,
  636.                             'user_logado' => $user_logado,
  637.                             'cliente' => $cliente,
  638.                             'cliente_session' => $cliente_session,
  639.                             'form' => $form->createView(),
  640.                                             ]);
  641.        
  642.     }
  643.     #[Route('/index'name'index')]
  644.     public function indexar(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManager SessionInterface $session): Response
  645.     {
  646.         $dotenv = new Dotenv();
  647.         $dotenv->load(__DIR__.'/.env');
  648.         $user_logado $this->getUser();
  649.         $form $this->createForm(UploadType::class);
  650.         $form->handleRequest($request);
  651.         $user_logado_tipoAcesso $user_logado->getTipoAcesso();
  652.         $user_logado_nome $user_logado->getNome();
  653.         $user_logado_id $user_logado->getId();
  654.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  655.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  656.         $hoje_formt=$hoje->format('Y-m-d');
  657.         $doc $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome$hoje_formt);
  658.         $dia_prod 'de hoje';
  659.         $permissao = [];
  660.         $list_indexador = [];
  661.          
  662.         if(isset($_POST["btn_cliente"])){
  663.             
  664.             $session->set('cliente_id'$_POST["btn_cliente"]);
  665.             return $this->redirectToRoute('home');
  666.         }
  667.         $clienteId $session->get('cliente_id');
  668.         if ($clienteId == null ) {
  669.             
  670.             $caixas =  "";
  671.             $index_all ="";
  672.             $documentos="";
  673.             $cliente_session "";
  674.        
  675.         } else {
  676.             
  677.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  678.             $caixas $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  679.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  680.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  681.             
  682.             
  683.         }
  684.        
  685.         if(isset($_POST["date_perio"])){
  686.             
  687.             
  688.             $startDate $_POST["de"];
  689.             $endDate $_POST["ate"];
  690.        
  691.             $de = new \DateTimeImmutable($startDate);
  692.             $ate = new \DateTimeImmutable($endDate);
  693.             $de_formt=$de->format('d/m/Y') ;
  694.             $ate_formt=$ate->format('d/m/Y') ;
  695.             
  696.             if($endDate != ""){ 
  697.                 
  698.                 $doc $entityManager->getRepository(Documento::class)->findByUserAndDateIndexRange($user_logado_nome$startDate$endDate);
  699.                 $dia_prod 'de '$de_formt.' até '.$ate_formt
  700.             
  701.             }
  702.             if($endDate == ""){ 
  703.                 
  704.                 $doc $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome$startDate);
  705.                 $dia_prod 'de '$de_formt
  706.             }
  707.             
  708.             
  709.             
  710.         }
  711.        
  712.         
  713.         foreach ($user_logado_tipoAcesso["new"] as  $value) {
  714.             
  715.             foreach ($index_all as $key) {
  716.                 if ( $key->getId() ==  $value) {
  717.                     
  718.                     $permissao[] = $value;
  719.                     
  720.                 }
  721.                
  722.             }
  723.         }
  724.     
  725.         $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null 'cliente' => $clienteId]);
  726.         
  727.         $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $clienteId]);
  728.         $cliente_id $doctrine->getRepository(Cliente::class)->findBy(['id' => $clienteId]);
  729.         
  730.        
  731.         
  732.         
  733.         foreach ($cliente_id as $cliente_ids) {
  734.             
  735.             $cliente_nome$cliente_ids->getNome();
  736.             $clientes$cliente_ids->getId();
  737.             $umlautString =$cliente_nome;
  738.             $slugger = new AsciiSlugger();
  739.             $teste=$slugger->slug($umlautString$seperator '-')->toString();
  740.             $caminho strtolower ($teste.'/');
  741.                         
  742.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  743.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  744.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  745.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  746.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  747.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  748.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  749.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  750.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  751.         }
  752.         
  753.         
  754.         
  755.         if ($clienteId == null ) {
  756.             
  757.             $caixas =  "";
  758.        
  759.         } else {
  760.             
  761.             $caixas $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  762.         }   
  763.             
  764.            
  765.         $erro '';
  766.         $ii=0;
  767.         $pagina 'index';
  768.         $p '';
  769.         $link '';
  770.         $mx 0;
  771.         $xy 
  772.         $yz 
  773.         $ay ;
  774.         $ky ;
  775.         $pdf ='';
  776.         $pagina_h4 ='Documento(s) para indexar';
  777.         $nome_menu_ '';
  778.         $index_tipo='';
  779.         $uuid Uuid::v4();
  780.         $user $this->getUser();
  781.         $user_nome$user->getEmail();
  782.         $user_nome_name$user->getNome();
  783.         $pasta_user=$user_nome.'/';
  784.         $arr = [];
  785.         $arrr=0;
  786.         $index_find null;
  787.         $dt '';
  788.         $clientS3 = new  S3Client([
  789.                     'region'  => 'sa-east-1',
  790.                     'version' => 'latest',
  791.                     'credentials' => [ 
  792.                         'key'    => $_ENV['AWS_KEY'],
  793.                         'secret' => $_ENV['AWS_SECRET'],
  794.                     ],
  795.                 ]);
  796.         
  797.      
  798.             
  799.         if(isset($_POST["dt"]))
  800.         {   
  801.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => $_POST["dt"]]);
  802.             $index_find =  $doctrine->getRepository(Tipo::class)->find($_POST["dt"]);
  803.             $pagina =$index_find->getNome();
  804.             $pagina_h4 ='Documento(s) do tipo ( '.$pagina.' )';
  805.             
  806.             
  807.         }
  808.        
  809.         if(isset($_POST["botao_index"])){
  810.             
  811.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  812.             $link $pdf->getImage();
  813.             $xy ;
  814.             
  815.         }
  816.         if(isset($_POST["botao_doc"])){
  817.             
  818.             
  819.             $yz ;
  820.             $xy ;
  821.             $ay ;
  822.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  823.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  824.            
  825.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  826.             $index_tipo_tipo =  $index_tipo->getNome();
  827.             $link $pdf->getImage();
  828.             $fase=$_POST["fase"];
  829.             $data $_POST["data"];
  830.             $cx $_POST["caixas"];
  831.             $classifica $_POST["classifica"];
  832.             $fase $_POST["fase"];
  833.             $desc $_POST["desc"];
  834.             $assunto $_POST["assunto"];
  835.             $chave $_POST["chave"];
  836.             $nome $_POST["nome"];
  837.             $conteiner $_POST["conteiner"];
  838.             
  839.           
  840.             
  841.             $caixa_id $doctrine->getRepository(Caixa::class)->find($cx);
  842.             
  843.             
  844.             
  845.             // Encontra todos os números na frase
  846.             preg_match_all('/\d+/'$fase$matches);
  847.             // $matches[0] agora contém todos os números encontrados na frase
  848.             $numeros array_map('intval'$matches[0]);
  849.             // Exibe os números encontrados
  850.             
  851.             if ($clientes != 7) {
  852.            
  853.                 if ($data != "") {
  854.                     
  855.                     if ($fase != "") {
  856.     
  857.                         // Número inteiro que você deseja somar ao ano
  858.                         $numeroParaSomar $numeros[0];
  859.     
  860.                         // Extrair o ano da data
  861.                         list($ano$mes$dia) = explode('-'$data);
  862.     
  863.                         // Converter o ano para um número inteiro
  864.                         $ano intval($ano);
  865.     
  866.                         // Somar o número ao ano
  867.                         $data_vecimento =  $ano $numeroParaSomar.'-'.$mes.'-'$dia;
  868.     
  869.                         $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  870.     
  871.                     }
  872.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  873.                 }
  874.             }    
  875.             
  876.             if ($clientes == 7) {
  877.                   
  878.                   $pdf->setVencimentoDocumento(new \DateTimeImmutable($fase));
  879.                   $pdf->setDataDocumento(new \DateTimeImmutable($data));
  880.              }
  881.              
  882.             $pdf->setAssunto($assunto);
  883.             if ($classifica != "") {
  884.                 $classifica_id $doctrine->getRepository(Classificacao::class)->find($classifica);
  885.                 $pdf->setClassificacao($classifica_id);
  886.             }
  887.             $pdf->setCaixa($caixa_id);
  888.             $pdf->setExtraFields($desc);
  889.             $pdf->setNome($nome);
  890.             $pdf->setKeywords($chave);
  891.             $pdf->setUserIndex($user_nome_name);
  892.             $pdf->setConteiner($conteiner);
  893.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  894.             $pdf->setTipo($index_tipo);
  895.             $entityManager->flush();
  896.             $id_pd $pdf->getId();    
  897.             $log = new Registro();
  898.             $log->setOperacao('Indexou o Documento com id '.$id_pd); 
  899.             $log->setUser($user_nome_name);
  900.             $log->setCliente($cliente_nome);
  901.             $entityManager->persist($log);
  902.             $entityManager->flush();
  903.             $erro 'ok';
  904.             $p =  $index_tipo_tipo.' indexado com sucesso';
  905.             
  906.            
  907.             
  908.            
  909.         }   
  910.         if(isset($_POST["botao_index_edit"])){
  911.             
  912.             $yz ;
  913.             $xy ;
  914.             $ay ;
  915.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  916.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  917.             $link $pdf->getImage();
  918.         }
  919.         if(isset($_POST["botao_volta"])){
  920.             $xy ;
  921.             $yz ;
  922.         }
  923.         if(isset($_POST["index_button"])){
  924.             
  925.             
  926.             $yz ;
  927.             $xy ;
  928.             $ay ;
  929.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  930.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["index_button"]);
  931.             $link $pdf->getImage();
  932.         }
  933.         if(isset($_POST["botao_cancel"])){
  934.             $yz ;
  935.             $xy ;
  936.             $ay ;
  937.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  938.             $link $pdf->getImage();
  939.             
  940.         }
  941.         if(isset($_POST["delet"])){
  942.            
  943.             $ky ;
  944.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["delet"]);
  945.             $documentos $doctrine->getRepository(Documento::class)->findBy(['id' => $_POST["delet"]]);
  946.             
  947.             if($pdf->getTipo()!= null){
  948.                 $index_find =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  949.                 $pagina =$index_find->getTipo();
  950.                 $pagina_h4 ='Documento(s) do tipo ( '.$index_find->getTipo().' )';
  951.             }
  952.                         
  953.         }
  954.         if(isset($_POST["delet_cancel"])){
  955.             $ky ;
  956.         }
  957.         if(isset($_POST["delet_sim"])){
  958.             
  959.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  960.             $id_pd $pdf->getId();
  961.             $entityManager->remove($pdf);
  962.             $entityManager->flush();
  963.           
  964.             $log = new Registro();
  965.             $log->setOperacao('Excluiu Documento com id '.$id_pd); 
  966.             $log->setUser($user_nome_name);
  967.             $log->setCliente($cliente_nome);
  968.             $entityManager->persist($log);
  969.             $entityManager->flush();
  970.             $erro 'ok';
  971.             $p 'Documento com id '.$id_pd.' excluido com sucesso '
  972.         }
  973.         if(isset($_POST["index_edit"])){
  974.             $yz ;
  975.             $xy ;
  976.             $ay ;
  977.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  978.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  979.             $link $pdf->getImage();
  980.         }
  981.        
  982.        
  983.         $cmd $clientS3->getCommand('GetObject', [
  984.                 'Bucket' => 'arquivosdoc',
  985.                 'Key'    => $caminho$link
  986.             ]);
  987.             
  988.             $req $clientS3->createPresignedRequest($cmd'+30 minutes');
  989.             $all_Url = (string) $req->getUri();
  990.         return $this->render('index/index1.html.twig', [
  991.             'documentos' => $documentos,
  992.             'xy' => $xy,
  993.             'yz' => $yz,
  994.             'ay'=>$ay,
  995.             'link' => $link,
  996.             'pdf'=>$pdf,
  997.             'p'=>$p,
  998.             'erro'=>$erro,
  999.             'index_all'=>$index_all,
  1000.             'index_tipo'=>$index_tipo,
  1001.             'ky'=>$ky,
  1002.             'pagina' => $pagina,
  1003.             'pagina_h4' =>$pagina_h4,
  1004.             'index_find'=>$index_find,
  1005.             'mx'=>$mx,
  1006.             'caixas' => $caixas,
  1007.             'class' => $class,
  1008.             'permissao'=>$permissao,
  1009.             'caminho' =>$caminho,
  1010.             'clientes' => $clientes,
  1011.             'doc'=>$doc,
  1012.             'dia_prod' => $dia_prod,
  1013.             'cliente_session' => $cliente_session,
  1014.             'all_Url'=>$all_Url
  1015.         ]);
  1016.     }
  1017.     
  1018.     #[Route('/index/novo/fluxo'name'fluxo_novo')]
  1019.     public function fluxoNovo(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer): Response
  1020.     {
  1021.         $user_logado $this->getUser();
  1022.         $user_logado_nome $user_logado->getNome();
  1023.         $user_logado_id $user_logado->getId();
  1024.         $erro '';
  1025.         $pagina 'fluxo';
  1026.         $p ='';
  1027.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  1028.         
  1029.         if(isset($_POST["btn_cliente"])){
  1030.             
  1031.             $session->set('cliente_id'$_POST["btn_cliente"]);
  1032.             return $this->redirectToRoute('home');
  1033.         }
  1034.         $clienteId $session->get('cliente_id');
  1035.         
  1036.       
  1037.         
  1038.         if ($clienteId == null ) {
  1039.             
  1040.             $cli =  "";
  1041.             return $this->redirectToRoute('home');
  1042.           
  1043.        
  1044.         } else {
  1045.             
  1046.          
  1047.             $cli $doctrine->getRepository(Cliente::class)->find($clienteId);
  1048.             
  1049.         }
  1050.         
  1051.         $query $doctrine->getManager()->createQuery('
  1052.             SELECT u
  1053.             FROM App\Entity\User u
  1054.             JOIN u.clientes c
  1055.             WHERE c.id = :clientId
  1056.             AND u.enabled = 1
  1057.         ')->setParameter('clientId'$clienteId);
  1058.         $usuarios $query->getArrayResult();
  1059.         if(isset($_POST["fluxo"])){
  1060.             
  1061.             $fluxo = new Fluxo();
  1062.             $nome $cli->getNome();
  1063.             $fluxo->setNome($nome);
  1064.             $fluxo->setUser($user_logado);
  1065.             $fluxo->setCliente($cli);
  1066.             $fluxo->setObs($_POST["obs"]);
  1067.             $entityManager->persist($fluxo);
  1068.             $entityManager->flush();
  1069.             $id_fluxo $fluxo->getId(); 
  1070.             
  1071.             $prazo $_POST["prazo"];
  1072.             $user_1 $_POST["user"];
  1073.             
  1074.             foreach ($user_1 as $users) {
  1075.                
  1076.                     $etapa = new Etapa();
  1077.                     $user $doctrine->getRepository(User::class)->find($users);
  1078.                     $mail $user->getEmail();
  1079.                     
  1080.                    
  1081.                     $etapa->setNome($_POST["etapa"]);
  1082.                     $etapa->setOrdem(1);
  1083.                     $etapa->setUser($user);
  1084.                     $etapa->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1085.                     $etapa->setPrazo(new \DateTimeImmutable($prazo));
  1086.                     $entityManager->persist($etapa);
  1087.                     $entityManager->flush();
  1088.         
  1089.                     /*$email = (new Email())
  1090.                         ->from('arquivosdoc@arquivosdoc.com.br')
  1091.                         ->to($mail)
  1092.                         ->subject('Fluxo de Trabalho')
  1093.                         ->html('<div style="text-align: center;">
  1094.                             <h1 style="color:#1e4067;">Recebimento<br>
  1095.                             Cliente: '.$nome.'<br>
  1096.                             Prazo:'.$prazo.'<br>
  1097.                             Enviado por: '.$user_logado_nome.'<br>
  1098.                             Acesse sua pagina inicial no <a href="https://ged.arquivosdoc.com.br/login">ArquivosGED
  1099.                             </a></h1>
  1100.                             <img src="cid:logo"><div>')
  1101.                         ->embed(fopen('C:/xampp8/htdocs/gedemail/public/img/icon.png', 'r'), 'logo', 'image/png');
  1102.                     $mailer->send($email);*/
  1103.                     
  1104.                  
  1105.             }
  1106.             
  1107.             if(isset($_POST["user_2"])){
  1108.                 
  1109.                 
  1110.                 $prazo_2 $_POST["prazo_2"];
  1111.                 $user_2 $_POST["user_2"];
  1112.                 foreach ($user_2 as $users2) {
  1113.                     $etapa2 = new Etapa();
  1114.                     $etapa2->setNome($_POST["etapa2"]);
  1115.                     $etapa2->setOrdem(2);
  1116.                     $etapa2->setUser($doctrine->getRepository(User::class)->find($users2));
  1117.                     $etapa2->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1118.                     $etapa2->setPrazo(new \DateTimeImmutable($prazo_2));
  1119.                     $entityManager->persist($etapa2);
  1120.                     $entityManager->flush();
  1121.                 }
  1122.             }
  1123.             if(isset($_POST["user_3"])){
  1124.                 
  1125.                 
  1126.                 $user_3 $_POST["user_3"];
  1127.                 $prazo_3 $_POST["prazo_3"];
  1128.                 foreach ($user_3 as $users3) {
  1129.                     $etapa3 = new Etapa();
  1130.                     $etapa3->setNome($_POST["etapa3"]);
  1131.                     $etapa3->setOrdem(3);
  1132.                     $etapa3->setUser($doctrine->getRepository(User::class)->find($users3));
  1133.                     $etapa3->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1134.                     $etapa3->setPrazo(new \DateTimeImmutable($prazo_3));
  1135.                     $entityManager->persist($etapa3);
  1136.                     $entityManager->flush();
  1137.                 }    
  1138.             }
  1139.             if(isset($_POST["user_4"])){
  1140.                 
  1141.                 $user_4 $_POST["user_4"];
  1142.                 $prazo_4 $_POST["prazo_4"];
  1143.                 foreach ($user_4 as $users4) {
  1144.                     $etapa4 = new Etapa();
  1145.                     $etapa4->setNome($_POST["etapa4"]);
  1146.                     $etapa4->setOrdem(4);
  1147.                     $etapa4->setUser($doctrine->getRepository(User::class)->find($users4));
  1148.                     $etapa4->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1149.                     $etapa4->setPrazo(new \DateTimeImmutable($prazo_4));
  1150.                     $entityManager->persist($etapa4);
  1151.                     $entityManager->flush();
  1152.                 }
  1153.             } 
  1154.             
  1155.             
  1156.             if(isset($_POST["user_5"])){
  1157.                 
  1158.                 $user_5 $_POST["user_5"];
  1159.                 $prazo_5 $_POST["prazo_5"];
  1160.                 foreach ($user_5 as $users5) {
  1161.                     $etapa5 = new Etapa();
  1162.                     $etapa5->setNome($_POST["etapa5"]);
  1163.                     $etapa5->setOrdem(5);
  1164.                     $etapa5->setUser($doctrine->getRepository(User::class)->find($users5));
  1165.                     $etapa5->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1166.                     $etapa5->setPrazo(new \DateTimeImmutable($prazo_5));
  1167.                     $entityManager->persist($etapa5);
  1168.                     $entityManager->flush();
  1169.                 }
  1170.             } 
  1171.             $erro "ok";
  1172.             $p =  'FLUXO ENVIADO' ;
  1173.             
  1174.             
  1175.         }
  1176.         
  1177.     
  1178.        
  1179.         return $this->render('index/index4.html.twig', [
  1180.     
  1181.             
  1182.             'p'=>$p,
  1183.             'erro'=>$erro,
  1184.             'pagina' => $pagina,
  1185.             'usuarios' =>$usuarios,
  1186.             'cliente' => $cliente
  1187.             
  1188.         ]);
  1189.     }
  1190.     #[Route('/index/fluxo'name'fluxo')]
  1191.     public function fluxoPaginatorInterface $paginator,Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer): Response
  1192.     {
  1193.         $user_logado $this->getUser();
  1194.         $erro '';
  1195.         $pagina 'fluxo';
  1196.         $p ='';
  1197.         $registro $doctrine->getRepository(Registro::class)->findAll();
  1198.         $a 0;
  1199.         $clientS3 = new  S3Client([
  1200.             'region'  => 'sa-east-1',
  1201.             'version' => 'latest',
  1202.             'credentials' => [ 
  1203.                 'key'    => $_ENV['AWS_KEY'],
  1204.                 'secret' => $_ENV['AWS_SECRET'],
  1205.             ],
  1206.         
  1207.         ]);
  1208.         
  1209.     
  1210.         if(isset($_POST["btn_cliente"])){
  1211.             
  1212.             $session->set('cliente_id'$_POST["btn_cliente"]);
  1213.             return $this->redirectToRoute('home');
  1214.         }
  1215.         $clienteId $session->get('cliente_id');
  1216.         
  1217.         if($clienteId == null){
  1218.             
  1219.             return $this->redirectToRoute('home');
  1220.         }
  1221.         
  1222.         
  1223.         $fluxo $doctrine->getRepository(Fluxo::class)->findBy(['cliente' => $clienteId],['id'=> 'DESC']);
  1224.       
  1225.         
  1226.         // Paginar os fluxos
  1227.         $fluxos $paginator->paginate(
  1228.             $fluxo// O queryBuilder ou a query
  1229.             $request->query->getInt('page'1), // A página atual, padrão é 1
  1230.             // O número de itens por página
  1231.         );
  1232.         if (isset($_POST["excel"])) {
  1233.             
  1234.         
  1235.             $cx null;
  1236.             $id_fluxo $_POST["excel"];
  1237.             $fluxo_excel $doctrine->getRepository(Fluxo::class)->find($id_fluxo);
  1238.             $nome_fluxo $fluxo_excel->getNome();
  1239.             $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_excel->getId());
  1240.             
  1241.             
  1242.         
  1243.             // Cria uma nova planilha
  1244.             $spreadsheet = new Spreadsheet();
  1245.             $sheet $spreadsheet->getActiveSheet();
  1246.             $sheet->setTitle('CAIXA(S)');
  1247.             // Configura o cabeçalho
  1248.             $sheet->setCellValue('A1''ID');
  1249.             $sheet->setCellValue('B1''REPOSITOR');
  1250.             $sheet->setCellValue('C1''DATA DO ENVIO');
  1251.         
  1252.             // Estiliza o cabeçalho (fundo azul, texto branco e negrito)
  1253.             $headerStyle = [
  1254.                 'font' => [
  1255.                     'bold' => true,
  1256.                     'color' => ['rgb' => 'FFFFFF'], // Texto branco
  1257.                 ],
  1258.                 'fill' => [
  1259.                     'fillType' => Fill::FILL_SOLID,
  1260.                     'startColor' => ['rgb' => '095f99'], // Fundo azul
  1261.                 ],
  1262.             ];
  1263.             $sheet->getStyle('A1:C1')->applyFromArray($headerStyle);
  1264.         
  1265.             // Preenche os dados
  1266.             $rowCount 2;
  1267.             foreach ($fluxo_caixas as $caixas) {
  1268.                 
  1269.                     if($caixas->getCx() != null){
  1270.                     
  1271.                     $nome $caixas->getNome();
  1272.                     $cx $caixas->getCx()->getNome();
  1273.                     $data $caixas->getCreatedAt();
  1274.             
  1275.                     // Insere os valores
  1276.                     $sheet->setCellValue('A' $rowCount$cx);
  1277.                     $sheet->setCellValue('B' $rowCount$nome);
  1278.             
  1279.                     // Converte a data para o formato Excel
  1280.                     if ($data instanceof \DateTime) {
  1281.                         $sheet->setCellValue('C' $rowCountDate::PHPToExcel($data));
  1282.                     } else {
  1283.                         $sheet->setCellValue('C' $rowCount$data); // Evita erro se não for DateTime
  1284.                     }
  1285.             
  1286.                     $rowCount++;
  1287.                 }
  1288.             }
  1289.         
  1290.             // Formata a coluna C como data (exceto o cabeçalho)
  1291.             $sheet->getStyle('C2:C' . ($rowCount 1))
  1292.                 ->getNumberFormat()
  1293.                 ->setFormatCode('dd/mm/yyyy');
  1294.         
  1295.             // Define largura automática das colunas
  1296.             foreach (range('A''C') as $col) {
  1297.                 $sheet->getColumnDimension($col)->setAutoSize(true);
  1298.             }
  1299.              // Segunda aba - Outras informações (Exemplo)
  1300.             $sheet2 $spreadsheet->createSheet(); // Cria uma nova aba
  1301.             $sheet2->setTitle('DOCUMENTO(S)'); // Renomeia a aba
  1302.             $sheet2->setCellValue('A1' 'ID');
  1303.             $sheet2->setCellValue('B1' 'NOME');
  1304.             $sheet2->setCellValue('C1' 'REPOSITOR');
  1305.             $sheet2->setCellValue('D1' 'TIPO');
  1306.             $sheet2->setCellValue('E1' 'ASSUNTO');
  1307.             $sheet2->setCellValue('F1' 'PALAVRA-CHAVE');
  1308.             $sheet2->setCellValue('G1' 'DIGITALIZAÇÃO');
  1309.             $sheet2->setCellValue('H1' 'QUEM DIGITALIZOU?');
  1310.             $sheet2->setCellValue('I1' 'INDEXAÇÃO');
  1311.             $sheet2->setCellValue('J1' 'QUEM INDEXOU?');
  1312.             $sheet2->setCellValue('K1' 'IMAGEN(S)');
  1313.             $sheet2->getStyle('A1:K1')->applyFromArray($headerStyle);
  1314.             
  1315.             $rowCount 2;
  1316.             foreach ($fluxo_caixas as $caixas) {
  1317.                 $doc $caixas->getDocumentos();
  1318.                 
  1319.                 foreach ($doc as $docs) {
  1320.                     $tiponull;
  1321.                     $id $docs->getId();
  1322.                     $nome $docs->getNome();
  1323.                     $caixa $docs->getCaixa()->getNome();
  1324.                     if($docs->getTipo() != null){
  1325.                         $tipo $docs->getTipo()->getNome();
  1326.                     }
  1327.                     $qtd $docs->getQtd();
  1328.                     $assunto $docs->getAssunto();
  1329.                     $keywords $docs->getKeywords();
  1330.                     $user $docs->getUser()->getNome();
  1331.                     $data  $docs->getCreatedAt();
  1332.                     $index  $docs->getIndexAt();
  1333.                     $user_index  $docs->getUserIndex();
  1334.                     $sheet2->setCellValue('A' $rowCount,$id);
  1335.                     $sheet2->setCellValue('B' $rowCount,$nome);
  1336.                     $sheet2->setCellValue('C' $rowCount,$caixa);
  1337.                     $sheet2->setCellValue('D' $rowCount,$tipo);
  1338.                     $sheet2->setCellValue('E' $rowCount,$assunto);
  1339.                     $sheet2->setCellValue('F' $rowCount,$keywords);
  1340.                     $sheet2->setCellValue('G' $rowCount,$data);
  1341.                     $sheet2->setCellValue('H' $rowCount,$user);
  1342.                     $sheet2->setCellValue('I' $rowCount,$index);
  1343.                     $sheet2->setCellValue('J' $rowCount,$user_index);
  1344.                     $sheet2->setCellValue('K' $rowCount,$qtd);
  1345.                    
  1346.                     
  1347.                     if ($data instanceof \DateTime) {
  1348.                         $sheet2->setCellValue('G' $rowCountDate::PHPToExcel($data));
  1349.                     } else {
  1350.                         $sheet2->setCellValue('G' $rowCount$data); // Evita erro se não for DateTime
  1351.                     }
  1352.                     if ($data instanceof \DateTime) {
  1353.                         $sheet2->setCellValue('I' $rowCountDate::PHPToExcel($index));
  1354.                     } else {
  1355.                         $sheet2->setCellValue('I' $rowCount$index); // Evita erro se não for DateTime
  1356.                     }
  1357.             
  1358.             
  1359.                     $rowCount++;
  1360.                 
  1361.                 }
  1362.             }
  1363.             $sheet2->getStyle('I2:I' . ($rowCount 1))
  1364.                 ->getNumberFormat()
  1365.                 ->setFormatCode('dd/mm/yyyy');
  1366.             $sheet2->getStyle('G2:G' . ($rowCount 1))
  1367.                 ->getNumberFormat()
  1368.                 ->setFormatCode('dd/mm/yyyy');    
  1369.         
  1370.             foreach (range('A''K') as $col) {
  1371.                 $sheet2->getColumnDimension($col)->setAutoSize(true);
  1372.             }
  1373.         
  1374.             // Gera o arquivo para download
  1375.             $writer = new Xlsx($spreadsheet);
  1376.             header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1377.             header('Content-Disposition: attachment; filename="' $nome_fluxo '-FLUXO-' $id_fluxo '.xlsx"');
  1378.             header('Cache-Control: max-age=0');
  1379.             $writer->save('php://output');
  1380.             exit;
  1381.         }
  1382.         if (isset($_POST["pdf"])) {
  1383.             
  1384.             $id_fluxo $_POST["pdf"];
  1385.             $fluxo_pdf $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  1386.             $nome_fluxo $fluxo_pdf->getNome();
  1387.             
  1388.            
  1389.             $html $this->render('index/pdf.html.twig', [
  1390.                 'fluxo_pdf' => $fluxo_pdf,
  1391.                 'registro' => $registro
  1392.                 
  1393.             ]);
  1394.             $options = new Options();
  1395.             $options->set('isHtml5ParserEnabled'true);
  1396.             $options->set('isPhpEnabled'true);
  1397.             $options->set('isRemoteEnabled'true); 
  1398.             $dompdf = new Dompdf($options);
  1399.             $dompdf->loadHtml($html);
  1400.             $dompdf->setPaper('A4''portrait');
  1401.             // Renderiza o HTML para o PDF
  1402.             $dompdf->render();
  1403.             // Envia o PDF para o navegador para download
  1404.             $dompdf->stream("Relatório_Fluxo_".$id_fluxo."_".$nome_fluxo.".pdf", ["Attachment" => 0]); // 0 para exibir no navegador, 1 para download
  1405.         }
  1406.         if (isset($_POST["etiqueta"])) {
  1407.             try {
  1408.         
  1409.                 // reforça limites (pode ajustar conforme necessário)
  1410.                 ini_set('max_execution_time'500);
  1411.                 ini_set('memory_limit''3512M');
  1412.         
  1413.                 $id_fluxo $_POST["etiqueta"];
  1414.                 $fluxo_pdf $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  1415.                 $cliente_id $fluxo_pdf->getCliente()->getId();
  1416.                 $cliente $doctrine->getRepository(Cliente::class)->findWithRelations($cliente_id);
  1417.                 $nome_fluxo $fluxo_pdf->getNome();
  1418.                 $clienteAll_fluxo $cliente->getClienteAll()->getLogo();
  1419.                 
  1420.                 $cmd $clientS3->getCommand('GetObject', [
  1421.                 'Bucket' => 'arquivosdoc',
  1422.                 'Key'    => 'LOGO_CLIENTES/'$clienteAll_fluxo
  1423.                 ]);
  1424.                 
  1425.                 $req $clientS3->createPresignedRequest($cmd'+30 minutes');
  1426.                 $cliente_all_Url = (string) $req->getUri();
  1427.                 
  1428.                 $clienteAll_fluxo_id $cliente->getClienteAll()->getId();
  1429.                 $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_pdf->getId());
  1430.                 if ($cliente_id == 139 or $cliente_id == 137){
  1431.                         $html '
  1432.                         <!DOCTYPE html>
  1433.                         <html lang="pt-BR">
  1434.                         <head>
  1435.                             <meta charset="UTF-8">
  1436.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1437.                             <title>FLUXO</title>
  1438.                             <style>
  1439.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  1440.                                 body { text-transform: uppercase; }
  1441.                                 .filho { border: 2px solid black; width: 57.2mm; height: 100mm; display: inline-block; margin: 2px; position: relative;}
  1442.                                 h2 { text-align: center; font-size: 20px; padding: 5px; }
  1443.                                 h2 img{width: 250px; height: 250px;}
  1444.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  1445.                                 h5 { text-align: center; font-size: 14px;}
  1446.                                 h6 { text-align: center; font-size: 14px; padding: 5px; }
  1447.                                 h5 img { text-align: center;max-height: 40px;width:auto;max-width: 40px}
  1448.                                 h6 img { text-align: center;margin:auto;  max-height: 130px;width:auto;max-width: 130px}
  1449.                                 p { text-align: center; font-size: 8px; font-weight: bold;}
  1450.                                 .pai { position: relative; top: 11%; }
  1451.                                 hr { color: black; }
  1452.                                 .lis2{
  1453.                                     
  1454.                                     font-weight: bold;
  1455.                                     margin:5px;
  1456.                                 }
  1457.                                 .lis3 {
  1458.                                     position: absolute;
  1459.                                     bottom: 0;
  1460.                                     width: 100%;
  1461.                                     font-weight: bold;
  1462.                                     text-align: center;
  1463.                                     margin-bottom:5px;
  1464.                                     margin-top:5px;
  1465.                                        
  1466.                                 }
  1467.                                 .lis{
  1468.                                     
  1469.                                     margin-left:10px;
  1470.                                     font-weight: bold;
  1471.                                 }
  1472.                                 li{
  1473.                                   margin:5px;
  1474.                                   font-size: 12px
  1475.                                 }
  1476.                                 
  1477.                             </style>
  1478.                         </head>
  1479.                         <body>
  1480.                         <div class="pai">';
  1481.                 
  1482.                         $count 0;
  1483.                 
  1484.                         foreach ($fluxo_caixas as $caixa) {
  1485.                             $count++;
  1486.                             $documento_fluxo $caixa->getDocumentos()->toArray();
  1487.                             
  1488.                 
  1489.                             $html .= '<div class="filho">
  1490.                                 
  1491.                                 
  1492.                                 <h6><img src="'.$cliente_all_Url.'" class="img"></h6>
  1493.                                 <hr>
  1494.                                 <h2>' htmlspecialchars($caixa->getNome()) . '</h2>
  1495.                                 <hr>
  1496.                                 ';
  1497.                 
  1498.                             $docs = [];
  1499.                             
  1500.                             if (!empty($documento_fluxo)) {
  1501.                                 foreach ($documento_fluxo as $doc) {
  1502.                                     if($doc->getTipo() != NULL ){
  1503.                                         if ($cliente_id != 122) {
  1504.                                             $docs[] = $doc->getTipo()->getNome();
  1505.                                         } else {
  1506.                                             $docs[] = $doc->getNome();
  1507.                                         }
  1508.                                     }
  1509.                                 }
  1510.                                 $docs array_unique($docs);
  1511.                             }
  1512.                             
  1513.                             
  1514.                             $docs_class = [];
  1515.                             
  1516.                             if (!empty($documento_fluxo)) {
  1517.                                 foreach ($documento_fluxo as $doc) {
  1518.                                     
  1519.                                     if($doc->getClassificacao() != NULL ){
  1520.                                        $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  1521.                                        $class_nome =  $clss[0]->getNome();
  1522.                                        $docs_class[] = $class_nome;
  1523.                                         
  1524.                                     }
  1525.                                 }
  1526.                                 $docs_class array_unique($docs_class);
  1527.                             }
  1528.                 
  1529.                             $docs_data = [];
  1530.                             $docs_assunto=[];
  1531.                             if (!empty($documento_fluxo)) {
  1532.                                 foreach ($documento_fluxo as $data) {
  1533.                                     if ($data->getNome() !== null) {
  1534.                                         $docs_data[] = $data->getNome();
  1535.                                     }
  1536.                                     if ($data->getAssunto() !== null) {
  1537.                                         $docs_assunto[] = $data->getAssunto();
  1538.                                     }
  1539.                                 }
  1540.                                 $docs_data array_unique($docs_data);
  1541.                                 $docs_assunto array_unique($docs_assunto);
  1542.                             }
  1543.                             
  1544.                              if ($cliente_id == 139){
  1545.                        
  1546.                                 $pl_numeros = [];
  1547.                                 $req_numeros = [];
  1548.                                 $req_ano null;
  1549.                                 
  1550.                                 foreach ($docs_data as $doc) {
  1551.                                 
  1552.                                 
  1553.                                     if (preg_match('/^PL-(\d{1,3}(?:\.\d{3})*)$/'$doc$m)) {
  1554.                                 
  1555.                                         $numeroLimpo str_replace('.'''$m[1]);
  1556.                                         $pl_numeros[] = (int)$numeroLimpo;
  1557.                                     }
  1558.                                 
  1559.                            
  1560.                                     elseif (stripos($doc'REQUERIMENTO') !== false 
  1561.                                         && preg_match('/-(\d+)\.(\d{4})$/'$doc$m)) {
  1562.                                 
  1563.                                         $req_numeros[] = (int)$m[1];
  1564.                                         $req_ano $m[2];
  1565.                                     }
  1566.                                 }
  1567.                                 
  1568.                         
  1569.                                 
  1570.                                 $menorNome null;
  1571.                                 $maiorNome null;
  1572.                                 $docs_faltantes = [];
  1573.                                 $tipoAtual null;
  1574.                                 
  1575.                           
  1576.                                 
  1577.                                 if (!empty($pl_numeros)) {
  1578.                                 
  1579.                                     sort($pl_numeros);
  1580.                                 
  1581.                                     $menor min($pl_numeros);
  1582.                                     $maior max($pl_numeros);
  1583.                                 
  1584.                                     $menorNome 'PL ' number_format($menor0'''.');
  1585.                                     $maiorNome 'PL ' number_format($maior0'''.');
  1586.                                 
  1587.                                     $esperado range($menor$maior);
  1588.                                     $faltantes array_diff($esperado$pl_numeros);
  1589.                                 
  1590.                                     foreach ($faltantes as $f) {
  1591.                                         $docs_faltantes[] = 'PL ' number_format($f0'''.');
  1592.                                     }
  1593.                                 
  1594.                                     $tipoAtual 'PL';
  1595.                                 }
  1596.                                 
  1597.                           
  1598.                                 
  1599.                                 elseif (!empty($req_numeros)) {
  1600.                                 
  1601.                                     sort($req_numeros);
  1602.                                 
  1603.                                     $menor min($req_numeros);
  1604.                                     $maior max($req_numeros);
  1605.                                 
  1606.                                     $menorNome str_pad($menor2'0'STR_PAD_LEFT) . '.' $req_ano;
  1607.                                     $maiorNome str_pad($maior2'0'STR_PAD_LEFT) . '.' $req_ano;
  1608.                                 
  1609.                                     $esperado range($menor$maior);
  1610.                                     $faltantes array_diff($esperado$req_numeros);
  1611.                                 
  1612.                                     foreach ($faltantes as $f) {
  1613.                                         $docs_faltantes[] = str_pad($f2'0'STR_PAD_LEFT) . '.' $req_ano;
  1614.                                     }
  1615.                                 
  1616.                                     $tipoAtual 'REQUERIMENTO';
  1617.                                 }                                                                        
  1618.                                                                                                                             
  1619.                                                                 
  1620.                                     $html .= '<h6>' htmlspecialchars(implode(', '$docs)) . '</h6>
  1621.                                     <hr>';
  1622.                                    
  1623.     
  1624.     
  1625.                                     $html .= '<h6>Conteúdo:</h6>';
  1626.     
  1627.                                     $html .= '<div class="lis">';
  1628.                                     foreach ($docs_class as $classs_nome) {
  1629.                                     $html .= '
  1630.                                         <li>' $classs_nome'</li>';
  1631.                                     }
  1632.                                     $html .= '</div><br>';
  1633.                                     
  1634.                                     
  1635.                                     if ($menorNome !== null && $maiorNome !== null) {
  1636.                                         $html .= '<h6>'.$menorNome.' Até '.$maiorNome.'</h6>';
  1637.                                     }
  1638.         
  1639.                                     if($docs_faltantes != []){
  1640.                                         $html .= '
  1641.                                         <div class="lis2"><p>';
  1642.                                                 $html .= 'Faltantes*</br>';
  1643.                                                 $qtdFaltantes count($docs_faltantes);
  1644.     
  1645.                                                 if ($qtdFaltantes 40) {
  1646.                                                 
  1647.                                                     $html .= '<span style="color:red; font-weight:bold;font-size: 8px">
  1648.                                                         Existem ' $qtdFaltantes . ($tipoAtual === 'PL' ' projetos de lei ' ' requerimentos ') . 'faltantes.
  1649.                                                         Conferir no inventário.
  1650.                                                     </span>';
  1651.                                                 
  1652.                                                 } else {
  1653.                                                 
  1654.                                                 $html .= implode(' | '$docs_faltantes);
  1655.     
  1656.                                                 
  1657.                                                 }
  1658.                                             
  1659.                                         $html .= '</p></div>';
  1660.                                     }
  1661.                                 }
  1662.                                 else{
  1663.                                     
  1664.                                                                 // Remove duplicados
  1665.                                 $docs_assunto array_unique($docs_assunto);
  1666.                                 
  1667.                                 // Converte para DateTime
  1668.                                 $datasObj array_map(function ($data) {
  1669.                                     return DateTime::createFromFormat('m/Y'$data);
  1670.                                 }, $docs_assunto);
  1671.                                 
  1672.                                 // Remove possíveis datas inválidas
  1673.                                 $datasObj array_filter($datasObj);
  1674.                                 
  1675.                                 // Ordena por data
  1676.                                 usort($datasObj, function ($a$b) {
  1677.                                     return $a <=> $b;
  1678.                                 });
  1679.                                 
  1680.                                 $resultado = [];
  1681.                                 
  1682.                                 if (count($datasObj) > 0) {
  1683.                                 
  1684.                                     $inicio $datasObj[0];
  1685.                                     $anterior $datasObj[0];
  1686.                                 
  1687.                                     for ($i 1$i count($datasObj); $i++) {
  1688.                                 
  1689.                                         $atual $datasObj[$i];
  1690.                                 
  1691.                                         $proximoEsperado = clone $anterior;
  1692.                                         $proximoEsperado->modify('+1 month');
  1693.                                 
  1694.                                         if ($atual->format('m/Y') !== $proximoEsperado->format('m/Y')) {
  1695.                                 
  1696.                                             if ($inicio->format('m/Y') === $anterior->format('m/Y')) {
  1697.                                                 $resultado[] = $inicio->format('m/Y');
  1698.                                             } else {
  1699.                                                 $resultado[] = $inicio->format('m/Y') . ' até ' $anterior->format('m/Y');
  1700.                                             }
  1701.                                 
  1702.                                             $inicio $atual;
  1703.                                         }
  1704.                                 
  1705.                                         $anterior $atual;
  1706.                                     }
  1707.                                 
  1708.                                     // Fecha o último bloco
  1709.                                     if ($inicio->format('m/Y') === $anterior->format('m/Y')) {
  1710.                                         $resultado[] = $inicio->format('m/Y');
  1711.                                     } else {
  1712.                                         $resultado[] = $inicio->format('m/Y') . ' Até ' $anterior->format('m/Y');
  1713.                                     }
  1714.                                 }
  1715.                                 
  1716.                                     
  1717.                                     
  1718.                                     
  1719.                                     
  1720.                                     $html .= '<h6>Conteúdo:</h6>';
  1721.     
  1722.                                     $html .= '<div class="lis">';
  1723.                                     foreach ($docs_class as $classs_nome) {
  1724.                                     $html .= '
  1725.                                         <li>' $classs_nome'</li>';
  1726.                                     }
  1727.                                     $len count($resultado);
  1728.                                     if ($len <and $len >0) {
  1729.                                          
  1730.                                          $html .= '<br>';     
  1731.                                     }
  1732.                                     foreach ($docs_data as $classs_nome) {
  1733.                                     $html .= '
  1734.                                         <h6>' $classs_nome'</h6>';
  1735.                                     }
  1736.                                     
  1737.                                     
  1738.                                     
  1739.                                         
  1740.                                     foreach ($resultado as $classs_nome) {
  1741.                                         if ($len >= 9) {
  1742.                                             $fontSize 8;
  1743.                                         } 
  1744.                                         elseif ($len <10 and $len >5) {
  1745.                                             $fontSize 10;
  1746.                                         }
  1747.                                         
  1748.                                         elseif ($len <and $len >0) {
  1749.                                             $fontSize 12;
  1750.                                              
  1751.                                         }else{
  1752.                                             $fontSize 8;
  1753.                                         }
  1754.                                         
  1755.                                     $html .= '
  1756.                                         <p style="font-size: ' $fontSize 'px;">' $classs_nome'</p>';
  1757.                                     }
  1758.                                     
  1759.                                     $html .= '</div><br>';
  1760.                                 }
  1761.                                 $html .= 
  1762.                                 
  1763.                                 
  1764.                                 '<div class="lis3"><hr>
  1765.                                 
  1766.                                 <p>ARQUIVOS GESTÃO DOCUMENTAL</p>
  1767.                                 <h5><img src="https://index.arquivosdoc.com.br/img/logo_menu.png" class="img"></h5>
  1768.                                 </div>
  1769.                                 
  1770.                             </div>';
  1771.                 
  1772.                             if ($count %  10 == 0) {
  1773.                                 $html .= '<div style="page-break-after: always;"></div>';
  1774.                             }
  1775.                         }
  1776.                
  1777.                         $html .= '</div></body></html>';
  1778.                 }
  1779.         
  1780.                 if($clienteAll_fluxo_id != 17 and $clienteAll_fluxo_id != 40 and $cliente_id != 139 and $cliente_id != 137){
  1781.                         // Construção do HTML com os QR Codes
  1782.                         $html '
  1783.                         <!DOCTYPE html>
  1784.                         <html lang="pt-BR">
  1785.                         <head>
  1786.                             <meta charset="UTF-8">
  1787.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1788.                             <title>FLUXO</title>
  1789.                             <style>
  1790.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  1791.                                 body { text-transform: uppercase; }
  1792.                                 .filho { border: 2px solid black; width: 120mm; height: 170mm; display: inline-block; margin-left: 45px; }
  1793.                                 h2 { text-align: center; font-size: 36px; padding: 5px; }
  1794.                                 h2 img{width: 200px; height: 200px;}
  1795.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  1796.                                 h5 { text-align: center; font-size: 22px; padding: 10px; }
  1797.                                 h6 { text-align: justify; font-size: 26px; padding: 5px; }
  1798.                                 h6 img { float: right;  max-height: 70px;width:auto;max-width: 170px}
  1799.                                 p { text-align: justify; font-size: 14px; font-weight: bold; padding: 10px; }
  1800.                                 .pai { position: relative; top: 20%; }
  1801.                                 hr { color: black; }
  1802.                                 .lis{
  1803.                                 
  1804.                                  width:430px; height: 200px;
  1805.                                  margin:auto;
  1806.                                  font-weight: bold;
  1807.                                 }
  1808.                                 li{
  1809.                                   margin-left:10px;
  1810.                                 }
  1811.                                 
  1812.                             </style>
  1813.                         </head>
  1814.                         <body>
  1815.                         <div class="pai">';
  1816.         
  1817.                         $count 0;
  1818.         
  1819.                         foreach ($fluxo_caixas as $caixa) {
  1820.                             $count++;
  1821.                             $documento_fluxo $caixa->getDocumentos()->toArray();
  1822.         
  1823.                             // Gerar QR Code
  1824.                             $qrCode Builder::create()
  1825.                                 ->writer(new PngWriter())
  1826.                                 ->data("https://ged.arquivosdoc.com.br/info/caixa/" $caixa->getId())
  1827.                                 ->build();
  1828.                             $qrCodeBase64 base64_encode($qrCode->getString());
  1829.         
  1830.                             $html .= '<div class="filho">
  1831.                                 <h2>' htmlspecialchars($caixa->getNome()) . '</h2>
  1832.                                 <hr>
  1833.                                 <h6>Arquivos:<img src="'.$cliente_all_Url.'" class="img"></h6>
  1834.                                 <p>' htmlspecialchars($fluxo_pdf->getNome()) . '</p>
  1835.                                 <hr>
  1836.                                 <h6>Título:</h6>';
  1837.         
  1838.                             $docs = [];
  1839.                             
  1840.                             if (!empty($documento_fluxo)) {
  1841.                                 foreach ($documento_fluxo as $doc) {
  1842.                                     if($doc->getTipo() != NULL ){
  1843.                                         if ($cliente_id != 122) {
  1844.                                             $docs[] = $doc->getTipo()->getNome();
  1845.                                         } else {
  1846.                                             $docs[] = $doc->getNome();
  1847.                                         }
  1848.                                     }
  1849.                                 }
  1850.                                 $docs array_unique($docs);
  1851.                             }
  1852.                             
  1853.                             $docs_class = [];
  1854.                             
  1855.                             if (!empty($documento_fluxo)) {
  1856.                                 foreach ($documento_fluxo as $doc) {
  1857.                                     
  1858.                                     if($doc->getClassificacao() != NULL ){
  1859.                                        $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  1860.                                        $class_nome =  $clss[0]->getNome();
  1861.                                        $docs_class[] = $class_nome;
  1862.                                        
  1863.                                         
  1864.                                     }
  1865.                                 }
  1866.                                 $docs_class array_unique($docs_class);
  1867.                             }
  1868.                             
  1869.         
  1870.                             $html .= '<p>' htmlspecialchars(implode(', '$docs)) . '</p>
  1871.                                 <hr>
  1872.                                 <h6>Conteúdo:</h6>';
  1873.                                 
  1874.                                 
  1875.                                 
  1876.                                   if($clienteAll_fluxo_id == 41){
  1877.                                       
  1878.                                         $html .= '<div class="lis">';
  1879.                                         $len count($docs_class);
  1880.                                      
  1881.                                         foreach ($docs_class as $classs_nome) {
  1882.                                         
  1883.                                         
  1884.                                             
  1885.                                             if ($len <= 9) {
  1886.                                                 $fontSize 16;
  1887.                                             } 
  1888.                                             elseif ($len <= 11) {
  1889.                                                 $fontSize 14;
  1890.                                             } 
  1891.                                             elseif ($len <= 13) {
  1892.                                                 $fontSize 12;
  1893.                                             } 
  1894.                                             elseif ($len <= 16) {
  1895.                                                 $fontSize 10;
  1896.                                             }
  1897.                                             elseif ($len <= 18) {
  1898.                                                 $fontSize 9;
  1899.                                             }
  1900.                                             elseif ($len <= 21) {
  1901.                                                 $fontSize =8;
  1902.                                             }
  1903.                                             elseif ($len <= 23) {
  1904.                                                 $fontSize 7;
  1905.                                             }
  1906.                                             else {
  1907.                                                 $fontSize 6;
  1908.                                             }
  1909.                                             $html .= '<li style="font-size: ' $fontSize 'px;">' $classs_nome '</li>';
  1910.                                         }
  1911.                                         
  1912.                                         $html .= '</div>';
  1913.                                         
  1914.                                       
  1915.                                   }else{
  1916.                                              $html .= '
  1917.                                                 <h2><img src="data:image/png;base64,' $qrCodeBase64 '" alt="QR Code"></h2>';
  1918.                                   }  
  1919.                                         
  1920.                                 
  1921.                                 
  1922.                                 $html .= '<hr>
  1923.                                 <h4>ARQUIVOS GESTÃO DOCUMENTAL</h4>
  1924.                                 <h5><img src="https://index.arquivosdoc.com.br/img/arquivos_mini.png" class="img"></h5>
  1925.                                 <hr>
  1926.                                 <h4>Etiqueta gerada automaticamente pelo ArquivosGED</h4>
  1927.                             </div>';
  1928.         
  1929.                             if ($count == 0) {
  1930.                                 $html .= '<div style="page-break-after: always;"></div>';
  1931.                             }
  1932.                         }
  1933.                
  1934.         
  1935.                         $html .= '</div></body></html>';
  1936.                 }
  1937.         
  1938.                 
  1939.                 if($clienteAll_fluxo_id == 17 ){
  1940.                     // Construção do HTML com os QR Codes
  1941.                     $html '
  1942.                     <!DOCTYPE html>
  1943.                     <html lang="pt-BR">
  1944.                     <head>
  1945.                         <meta charset="UTF-8">
  1946.                         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1947.                         <title>FLUXO</title>
  1948.                         <style>
  1949.                             * { margin: 0; padding: 0; font-family: Calibri, sans-serif; }
  1950.                             .filho { border: 2px solid black; width: 125mm; height: 170mm; display: inline-block; margin-left: 45px; }
  1951.                             h2 { font-size: 36px; padding: 5px; }
  1952.                             h2 img{width: 200px; height: 200px;}
  1953.                             .img_footer{width: 60px; height: 60px;position:relative;top:20px}
  1954.                             h4 { text-align: center; font-size: 12px; padding: 10px; }
  1955.                             h5 { text-align: center; font-size: 22px; padding: 10px; }
  1956.                             h6 { text-align: justify; font-size: 26px; padding: 5px; }
  1957.                             h6 img { float: right;  max-height: 77px;width:auto;max-width: 250px}
  1958.                             p { text-align: justify; font-size: 18px; font-weight: bold; padding: 10px; }
  1959.                             .pai { position: relative; top: 20%; }
  1960.                             hr { color: black; }
  1961.                             .rodape {
  1962.                                 position:relative;bottom:15px
  1963.                             }
  1964.         
  1965.                             
  1966.                         </style>
  1967.                     </head>
  1968.                     <body>
  1969.                     <div class="pai">';
  1970.             
  1971.                     $count 0;
  1972.         
  1973.                     $codigo "";
  1974.                     $info "";
  1975.                     $prazo "";
  1976.         
  1977.                     if($cliente_id == 113){
  1978.                         $codigo "23.182";
  1979.                         $info "PROCESSOS DIVERSOS";
  1980.                         $prazo "57 ANOS";
  1981.                     }
  1982.         
  1983.                     if($cliente_id == 114){                        
  1984.                         $codigo "23.11";
  1985.                         $info "PROCESSOS DE RECURSOS HUMANOS";
  1986.                         $prazo "100 ANOS";
  1987.                     }
  1988.             
  1989.                     foreach ($fluxo_caixas as $caixa) {
  1990.         
  1991.         
  1992.                         $texto $caixa->getNome();
  1993.         
  1994.                         preg_match_all('/\d+/'$texto$matches);
  1995.                         
  1996.                         if (count($matches[0]) >= 2) {
  1997.                              $numero str_pad($matches[0][0], 3'0'STR_PAD_LEFT); 
  1998.                             $ano substr($textostrpos($texto$matches[0][0]) + strlen($matches[0][0])); 
  1999.                             $ano trim(str_replace('-'''$ano)); 
  2000.                         } else {
  2001.                             echo "Formato inválido!";
  2002.                         }
  2003.         
  2004.         
  2005.         
  2006.                         $count++;
  2007.                         $documento_fluxo $caixa->getDocumentos()->toArray();
  2008.         
  2009.                         // Gerar QR Code
  2010.                         $qrCode Builder::create()
  2011.                             ->writer(new PngWriter())
  2012.                             ->data("https://ged.arquivosdoc.com.br/info/caixa/" $caixa->getId())
  2013.                             ->build();
  2014.                         $qrCodeBase64 base64_encode($qrCode->getString());
  2015.             
  2016.                         $html .= '<div class="filho">
  2017.                             <h2>&nbsp;Caixa nº&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'htmlspecialchars($numero) . '</h2>
  2018.                             <hr>
  2019.                             <h6>ARQUIVO:<img src="'.$cliente_all_Url'" class="img"></h6>
  2020.                             <p>SAAE VOLTA REDONDA-RJ</p>
  2021.                             <hr>
  2022.                             <h6>CÓDIGO TEMPORALIDADE:</h6>
  2023.                             <p>'.$codigo.'</p><hr>
  2024.                             <h6>TÍTULO:</h6>';
  2025.             
  2026.         
  2027.                         $html .= '<p>' htmlspecialchars('PROCESSOS ADMINISTRATIVOS') . '</p>
  2028.                             <hr>
  2029.                             <h6>INFORMAÇÕES:</h6>
  2030.                             <p>'.$info.'</p>
  2031.                             <hr>
  2032.                             <h6>PRAZO DE GUARDA:</h6>
  2033.                             <p>'.$prazo.'</p>
  2034.                             <hr>
  2035.                             <h6>DATA:</h6>
  2036.                             <p>'.$ano.'</p>
  2037.                             <hr>
  2038.                            
  2039.                                 <p class="rodape">&nbsp;ARQUIVOS GESTÃO DOCUMENTAL&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  2040.                                 <img src="https://index.arquivosdoc.com.br/img/arquivos_mini.png" class="img_footer"></p>
  2041.                            
  2042.                             </div>';
  2043.             
  2044.                         if ($count == 0) {
  2045.                             $html .= '<div style="page-break-after: always;"></div>';
  2046.                         }
  2047.                     }
  2048.            
  2049.         
  2050.                     $html .= '</div></body></html>';
  2051.                 }
  2052.                 
  2053.                 if($clienteAll_fluxo_id == 40  ){
  2054.                         $documento_all_sebrae $doctrine->getRepository(Documento::class)
  2055.                         ->findBy(
  2056.                             ['cliente' => $cliente_id], // filtros
  2057.                             ['id' => 'DESC'],            // ordenação (opcional)
  2058.                             100,                        // LIMIT
  2059.                             0                           // OFFSET
  2060.                         );
  2061.                         $html '
  2062.                         <!DOCTYPE html>
  2063.                         <html lang="pt-BR">
  2064.                         <head>
  2065.                             <meta charset="UTF-8">
  2066.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2067.                             <title>FLUXO</title>
  2068.                             <style>
  2069.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  2070.                                 body { text-transform: uppercase; }
  2071.                                 .filho { border: 2px solid black; width: 120mm; height: 160mm; display: inline-block; margin-left: 20px;padding:10px;} 
  2072.                                 h2 { text-align: center; font-size: 36px; padding: 5px; }
  2073.                                 h2 img{width: 200px; height: 200px;}
  2074.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  2075.                                 h5 { text-align: center; font-size: 22px; padding: 10px; }
  2076.                                 h6 { text-align: justify; font-size: 26px; padding: 5px; }}
  2077.                                 p { text-align: justify; font-size: 18px; font-weight: bold; padding: 10px; }
  2078.                                 .pai { position: relative; top: 20%;text-align:center; }
  2079.                                 hr { color: black; }
  2080.                                 
  2081.                                     .linha {
  2082.                                         margin-bottom: 1mm;
  2083.                                         font-size: 10pt;
  2084.                                     }
  2085.                                     .box-label {
  2086.                                         background: #f1f1f1;
  2087.                                         border: 1px solid black;
  2088.                                         padding: 1mm;
  2089.                                         font-size: 8pt;
  2090.                                         text-align: center;
  2091.                                         margin-top: 1mm;
  2092.                                     }
  2093.                                     .box-value {
  2094.                                         text-align: center;
  2095.                                         font-size: 10pt;
  2096.                                         margin: 2mm 0 2mm 0;
  2097.                                         
  2098.                                     }
  2099.                                    .box-value_conteudo {
  2100.                                         margin: 2mm 0 2mm 0;
  2101.                                         text-align: justify;
  2102.                                        
  2103.                                     }
  2104.                                     
  2105.                                     img{
  2106.                                         width: 120px;
  2107.                                         height:80px;
  2108.                                         margin: 2mm 0 2mm 0;
  2109.                                     }
  2110.                                     
  2111.                                     .titulo{
  2112.                                         margin: 2mm 0 2mm 0;
  2113.                                         font-size: 10pt;
  2114.                                     }
  2115.                                     
  2116.                                     .bloco-conteudo {
  2117.                                         position: relative;
  2118.                                         height: 100%;
  2119.                                     }
  2120.                                     
  2121.                                     .hr-fixo {
  2122.                                         position: absolute;
  2123.                                         bottom: 0;
  2124.                                         left: 0;
  2125.                                         width: 100%;
  2126.                                         margin: 0 0 0 0;
  2127.                                     }
  2128.                                     
  2129.                                 
  2130.                             </style>
  2131.                         </head>
  2132.                         <body>
  2133.                         <div class="pai">';
  2134.                 
  2135.                         $count 0;
  2136.                 
  2137.                         foreach ($documento_all_sebrae as $caixa) {
  2138.                             $count++;
  2139.                                 $conteudo htmlspecialchars(str_replace('?'''$caixa->getExtraFields()));
  2140.                                 $tamanho strlen($conteudo);
  2141.                                 $dates="";
  2142.                             
  2143.                                 if ($tamanho <= 300) {
  2144.                                     $fontSize '8pt';
  2145.                                 } elseif ($tamanho <= 600) {
  2146.                                     $fontSize '7pt';
  2147.                                 } elseif ($tamanho <= 900) {
  2148.                                     $fontSize '6pt';
  2149.                                 } else {
  2150.                                     $fontSize '4pt';
  2151.                                 }
  2152.                                 
  2153.                                 if($caixa->getDataDocumento()){
  2154.                                     $dates=$caixa->getDataDocumento()->format('d/m/Y');
  2155.                                 }
  2156.                             
  2157.                                 $html .= 
  2158.                                     '<div class="filho">
  2159.                                         <div class="bloco-conteudo">
  2160.                                         
  2161.                                             <img src="'.$cliente_all_Url.'" class="img"></h6>
  2162.                             
  2163.                                             <div class="titulo">ARQUIVO INATIVO</div><br>
  2164.                             
  2165.                                             <div class="linha">CAIXA Nº: _______________</div>
  2166.                             
  2167.                                             <div class="box-label">ÁREA/SIGLA:</div>
  2168.                                             <div class="box-value">'htmlspecialchars($caixa->getAssunto()) .'</div>
  2169.                             
  2170.                                             <div class="box-label">RESPONSÁVEL:</div>
  2171.                                             <div class="box-value">'htmlspecialchars($caixa->getConteiner()) .'</div>
  2172.                             
  2173.                                             <div class="box-label">DATA 1º ENVIO:</div>
  2174.                                             <div class="box-value">'htmlspecialchars($dates) .'</div>
  2175.                             
  2176.                                             <div class="box-label">Conteúdo</div>
  2177.                                             <div class="box-value_conteudo" style="font-size: '$fontSize .'">'$conteudo .'</div>
  2178.                                             
  2179.                                             <div class="hr-fixo">
  2180.                                                 <hr>
  2181.                                                 <div>CXRBM:'htmlspecialchars($caixa->getNome()) .'</div>
  2182.                                             </div>
  2183.                             
  2184.                                         </div>
  2185.         </div>';
  2186.                             $docs = [];
  2187.                             if ($count == 0) {
  2188.                                 $html .= '<div style="page-break-after: always;"></div>';
  2189.                             }
  2190.                         }
  2191.                
  2192.                         $html .= '</div></body></html>';
  2193.                 }
  2194.                         
  2195.                
  2196.                
  2197.                 // Configurar o Dompdf
  2198.                 $options = new Options();
  2199.                 $options->set('isHtml5ParserEnabled'true);
  2200.                 $options->set('isPhpEnabled'true);
  2201.                 $options->set('isRemoteEnabled'true);
  2202.                 $dompdf = new Dompdf($options);
  2203.                 $dompdf->loadHtml($html);
  2204.                 $dompdf->setPaper('A4''landscape');
  2205.         
  2206.                 // LIMPA TODOS OS BUFFERS ANTES DE RENDERIZAR
  2207.                 while (ob_get_level()) {
  2208.                     ob_end_clean();
  2209.                 }
  2210.         
  2211.                 // Tenta renderizar e, em vez de stream() direto, grava em arquivo temporário e envia
  2212.                 try {
  2213.                     $dompdf->render();
  2214.                 } catch (Throwable $e) {
  2215.                     // registra o erro e lança para cair no catch externo
  2216.                     error_log('Dompdf render failed: ' $e->getMessage());
  2217.                     throw $e;
  2218.                 }
  2219.         
  2220.                 // Gera arquivo temporário seguro
  2221.                 $tempFile sys_get_temp_dir() . DIRECTORY_SEPARATOR 'etiqueta_fluxo_' $id_fluxo '_' uniqid() . '.pdf';
  2222.                 $output $dompdf->output();
  2223.         
  2224.                 if (file_put_contents($tempFile$output) === false) {
  2225.                     throw new Exception('Falha ao escrever arquivo temporário do PDF.');
  2226.                 }
  2227.         
  2228.                 // Força headers corretos para download/visualização
  2229.                 header('Content-Type: application/pdf');
  2230.                 // Se quiser forçar download use attachment; se quiser abrir no browser use inline
  2231.                 header('Content-Disposition: inline; filename="Etiqueta_Fluxo_' preg_replace('/[^A-Za-z0-9_\-\.]/''_'$id_fluxo '_' $nome_fluxo) . '.pdf"');
  2232.                 header('Content-Length: ' filesize($tempFile));
  2233.                 header('Cache-Control: private, max-age=0, must-revalidate');
  2234.         
  2235.                 // Envia o arquivo binário ao navegador
  2236.                 readfile($tempFile);
  2237.         
  2238.                 // Remove o arquivo temporário com segurança
  2239.                 @unlink($tempFile);
  2240.         
  2241.                 // finaliza execução
  2242.                 exit;
  2243.         
  2244.                 
  2245.             } catch (Exception $e) {
  2246.                 // Loga para diagnóstico e mostra mensagem amigável
  2247.                 error_log('Erro ao gerar o PDF: ' $e->getMessage());
  2248.                 echo 'Erro ao gerar o PDF: ' htmlspecialchars($e->getMessage());
  2249.             }
  2250.         
  2251.         
  2252. }
  2253.         
  2254.         if (isset($_POST["qrcode"])) {
  2255.                 $id_fluxo $_POST["qrcode"];
  2256.                 $fluxo_qrcode $doctrine->getRepository(Fluxo::class)->findWithAllRelations($_POST["qrcode"]);
  2257.                 $nome_fluxo $fluxo_qrcode->getNome();
  2258.                 $fluxo_caixas_qrcode $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_qrcode->getId());
  2259.                 $clienteAll_id $fluxo_qrcode->getCliente()->getId();
  2260.                 
  2261.                 if ($fluxo_caixas_qrcode != null ) {
  2262.                     $options = new Options();
  2263.                     $options->set('isHtml5ParserEnabled'true);
  2264.                     $options->set('isPhpEnabled'true);
  2265.                     $dompdf = new Dompdf($options);
  2266.                             
  2267.                     $html '
  2268.                         <html>
  2269.                             <head>
  2270.                                 <style>
  2271.                                     @page {
  2272.                                         margin: 35px 18.9px 0px 18.9px;
  2273.                                         size: 210mm 297mm; /* Ajuste de tamanho do papel */
  2274.                                     }
  2275.                                     body {
  2276.                                         margin: 0;
  2277.                                         padding: 0;
  2278.                                     }
  2279.                                     .qr-item {
  2280.                                         border: 2px dotted #000;
  2281.                                         text-align: center;
  2282.                                         width: 32.27mm;
  2283.                                         height: 34.9mm; 
  2284.                                         display: inline-block;
  2285.                                     }
  2286.                         
  2287.                                     .qr-item img {
  2288.                                         width: 115px; 
  2289.                                         height: 112px;
  2290.                                     }
  2291.                                     .qr-title {
  2292.                                         font-size: 16px;
  2293.                                         font-weight: bold;
  2294.                                     }
  2295.                                     .leo {
  2296.                                         display: flex;
  2297.                                         flex-wrap: wrap;
  2298.                                     }
  2299.                                 </style>
  2300.                             </head>
  2301.                             <body>';
  2302.             
  2303.                     $count 0// Contador de QR Codes
  2304.             
  2305.                     foreach ($fluxo_caixas_qrcode as $cx) {
  2306.                         $id_cx_ultimo $cx->getCx();
  2307.             
  2308.                         if ($id_cx_ultimo !== null) {
  2309.                             $nome $id_cx_ultimo->getNome();
  2310.             
  2311.                             // Gerar QR Code com imagem no centro
  2312.                             $result Builder::create()
  2313.                                 ->writer(new PngWriter())
  2314.                                 ->writerOptions([])
  2315.                                 ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$nome)
  2316.                                 ->encoding(new Encoding('UTF-8'))
  2317.                                 ->size(500)
  2318.                                 ->margin(5)
  2319.                                 ->logoPath(__DIR__ '/logo.png'// Caminho do logo central
  2320.                                 ->build();
  2321.                             
  2322.                             // Salvar QR Code como arquivo temporário
  2323.                             $tempFile tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  2324.                             $result->saveToFile($tempFile);
  2325.             
  2326.                             // Adicionar QR Code ao HTML
  2327.                             if ($count 48 == 0) {
  2328.                                 $html .= '<div class="leo">';
  2329.                             }
  2330.             
  2331.                             $html .= '<div class="qr-item">';
  2332.                             $html .= '<div class="qr-title">' $nome '</div>';
  2333.                             $html .= '<img src="data:image/png;base64,' base64_encode(file_get_contents($tempFile)) . '">';
  2334.                             $html .= '</div>';
  2335.             
  2336.                             $count++;
  2337.             
  2338.                             // Fechar a div e inserir quebra de página a cada 63 QR Codes
  2339.                             if ($count 48 == 0) {
  2340.                                 $html .= '</div><div style="page-break-after: always;"></div>';
  2341.                             }
  2342.                         }
  2343.                     }
  2344.             
  2345.                     // Fechar qualquer div aberta sem completar 63 itens
  2346.                     if ($count 48 != 0) {
  2347.                         $html .= '</div>';
  2348.                     }
  2349.             
  2350.                     $html .= '</body></html>';
  2351.             
  2352.                     // Carregar o HTML e gerar o PDF
  2353.                     $dompdf->loadHtml($html);
  2354.                     $dompdf->setPaper([00210297], 'portrait'); // Configurar o tamanho de página para A4
  2355.                     $dompdf->render();
  2356.                     $dompdf->stream("Qrcode_" $id_fluxo "_" $nome_fluxo ".pdf", ["Attachment" => ]);
  2357.                 } else {
  2358.                     echo "<script>alert('ERROR, ESSE FLUXO NÃO TEM SETOR DE GUARDA!');</script>";
  2359.                 }
  2360.             }
  2361.         
  2362.         if (isset($_POST["container"])) {
  2363.             $id_fluxo $_POST["container"];
  2364.             $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($id_fluxo);
  2365.             $fluxo_container $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  2366.             $clienteAll_id $fluxo_container->getCliente()->getId();
  2367.             $containers = [];
  2368.         
  2369.             foreach ($fluxo_caixas as $caixa) {
  2370.                 $documentos $caixa->getDocumentos();
  2371.         
  2372.                 foreach ($documentos as $documento) {
  2373.                     $container $documento->getConteiner(); 
  2374.                     $caixaId $documento->getCaixa()->getId(); 
  2375.                     
  2376.                     if ($container != null and $caixaId != null) {
  2377.                         
  2378.                         if (!isset($containers[$container])) {
  2379.                             $containers[$container] = [];
  2380.                         }
  2381.         
  2382.                         if (!in_array($caixaId$containers[$container])) {
  2383.                             $containers[$container][] = $caixaId;
  2384.                         }
  2385.                     }
  2386.                 }
  2387.             }
  2388.             
  2389.             $options = new Options();
  2390.             $options->set('isHtml5ParserEnabled'true);
  2391.             $options->set('isPhpEnabled'true);
  2392.             $dompdf = new Dompdf($options);
  2393.                     
  2394.             $html '
  2395.                 <html>
  2396.                     <head>
  2397.                         <style>
  2398.                             @page {
  2399.                                 margin: 35px 18.9px 0px 18.9px;
  2400.                                 size: 210mm 297mm; /* Ajuste de tamanho do papel */
  2401.                             }
  2402.                             body {
  2403.                                 margin: 0;
  2404.                                 padding: 0;
  2405.                             }
  2406.                             .qr-item {
  2407.                                 border: 2px dotted #000;
  2408.                                 width: 200mm;
  2409.                                 height: 80mm;
  2410.                                 margin-top:15px; 
  2411.                                 text-align: center;
  2412.                                
  2413.                                 
  2414.                             }
  2415.                              .img_qrcode h2{                           
  2416.                                position:relative;
  2417.                                top:25px;
  2418.                             }
  2419.                             .img_qrcode h3{                           
  2420.                                position:relative;
  2421.                                bottom:25px;
  2422.                                font-size: 20px;
  2423.                             }
  2424.                             .img_qrcode{
  2425.                                
  2426.                                 display: inline-block;
  2427.                                 margin: 5px  30px 5px 30px;
  2428.                                
  2429.                                
  2430.                             }
  2431.                 
  2432.                             .qr-item img {
  2433.                                 
  2434.                                 width: 170px; 
  2435.                                 height: 170px;
  2436.                                 
  2437.                             }
  2438.                             .qr-title {
  2439.                                 font-size: 70px;
  2440.                                 font-weight: bold;
  2441.                                
  2442.                             }
  2443.                             .leo {
  2444.                                 display: flex;
  2445.                                 flex-wrap: wrap;
  2446.                             }
  2447.                         </style>
  2448.                     </head>
  2449.                     <body>';
  2450.     
  2451.             $count 0// Contador de QR Codes
  2452.             // Exibir resultado
  2453.             foreach ($containers as $container => $caixas) {
  2454.                 #echo "Container $container => " . implode(", ", $caixas) . "<br>";
  2455.                 
  2456.                
  2457.                 if ($count == 0) {
  2458.                     $html .= '<div class="leo">';
  2459.                 }
  2460.                 $html .= '<div class="qr-item">';
  2461.                 $html .= '<div class="qr-title">' $container '</div><hr>';
  2462.                 foreach($caixas as $caixa ){
  2463.                     $caix $doctrine->getRepository(Caixa::class)->find($caixa);
  2464.                     $caix_nome =$caix->getNome();
  2465.                     $caix_cx =$caix->getCx()->getNome();
  2466.                     $result Builder::create()
  2467.                     ->writer(new PngWriter())
  2468.                     ->writerOptions([])
  2469.                     ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$caix_cx)
  2470.                     ->encoding(new Encoding('UTF-8'))
  2471.                     ->size(350)
  2472.                     ->margin(5)
  2473.                     ->logoPath(__DIR__ '/logo.png'
  2474.                     ->build();
  2475.                 
  2476.                 
  2477.                     $tempFile tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  2478.                     $result->saveToFile($tempFile);
  2479.                     
  2480.                     $html .= '
  2481.                         <div class="img_qrcode">    
  2482.                             <h2>'.$caix_cx.'</h2>
  2483.                             <img src="data:image/png;base64,' base64_encode(file_get_contents($tempFile)) . '">
  2484.                             <h3>'.$caix_nome.'</h3>
  2485.                         </div>
  2486.                     
  2487.                     ';
  2488.                 }
  2489.                 $html .= '</div>';
  2490.                 $count++;
  2491.                 
  2492.                 if ($count == 0) {
  2493.                     $html .= '</div><div style="page-break-after: always;"></div>';
  2494.                 }
  2495.             }
  2496.               // Fechar qualquer div aberta sem completar 63 itens
  2497.               if ($count != 0) {
  2498.                 $html .= '</div>';
  2499.             }
  2500.     
  2501.             $html .= '</body></html>';
  2502.     
  2503.             // Carregar o HTML e gerar o PDF
  2504.             $dompdf->loadHtml($html);
  2505.             $dompdf->setPaper([00210297], 'portrait'); // Configurar o tamanho de página para A4
  2506.             $dompdf->render();
  2507.             $dompdf->stream("Qrcode.pdf", ["Attachment" => ]);
  2508.             
  2509.         }
  2510.         
  2511.         if (isset($_POST["pasta"])) {
  2512.             
  2513.                 // reforça limites (pode ajustar conforme necessário)
  2514.                 ini_set('max_execution_time'500);
  2515.                 ini_set('memory_limit''3512M');
  2516.         
  2517.                 $id_fluxo $_POST["pasta"];
  2518.                 $fluxo_pdf $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  2519.                 $cliente_id $fluxo_pdf->getCliente()->getId();
  2520.                 $cliente $doctrine->getRepository(Cliente::class)->findWithRelations($cliente_id);
  2521.                 $nome_fluxo $fluxo_pdf->getNome();
  2522.                 $clienteAll_fluxo $cliente->getClienteAll()->getLogo();
  2523.                 
  2524.                 $cmd $clientS3->getCommand('GetObject', [
  2525.                 'Bucket' => 'arquivosdoc',
  2526.                 'Key'    => 'LOGO_CLIENTES/'$clienteAll_fluxo
  2527.                 ]);
  2528.                 
  2529.                 $req $clientS3->createPresignedRequest($cmd'+30 minutes');
  2530.                 $cliente_all_Url = (string) $req->getUri();
  2531.                 
  2532.                 $clienteAll_fluxo_id $cliente->getClienteAll()->getId();
  2533.                 $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_pdf->getId());
  2534.                  $html '
  2535.                         <!DOCTYPE html>
  2536.                         <html lang="pt-BR">
  2537.                         <head>
  2538.                             <meta charset="UTF-8">
  2539.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2540.                             <title>FLUXO</title>
  2541.                             <style>
  2542.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  2543.                                 body { text-transform: uppercase; }
  2544.                                 .filho { border: 2px solid black; width: 50mm; height: 144mm; display: inline-block; margin: 2px; position: relative;}
  2545.                                 h2 { text-align: center; font-size: 20px; padding: 5px; }
  2546.                                 h2 img{width: 250px; height: 250px;}
  2547.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  2548.                                 h5 { text-align: center; font-size: 14px;}
  2549.                                 h6 { text-align: center; font-size: 14px; padding: 5px; }
  2550.                                 h5 img { text-align: center;max-height: 40px;width:auto;max-width: 40px}
  2551.                                 h6 img { text-align: center;margin:auto;  max-height: 130px;width:auto;max-width: 130px}
  2552.                                 p { text-align: center; font-size: 8px; font-weight: bold;}
  2553.                                 .pai { position: relative; top: 11%; }
  2554.                                 hr { color: black; }
  2555.                                 .lis2{
  2556.                                     
  2557.                                     font-weight: bold;
  2558.                                 }
  2559.                                 .lis3 {
  2560.                                     position: absolute;
  2561.                                     bottom: 0;
  2562.                                     width: 100%;
  2563.                                     font-weight: bold;
  2564.                                     text-align: center;
  2565.                                     margin-bottom:5px;
  2566.                                     margin-top:5px;
  2567.                                        
  2568.                                 }
  2569.                                 .lis{
  2570.                                     
  2571.                                     margin-left:10px;
  2572.                                     font-weight: bold;
  2573.                                 }
  2574.                                 li{
  2575.                                    font-size: 12px;
  2576.                                    margin-left:2px;
  2577.                                 }
  2578.                                 
  2579.                             </style>
  2580.                         </head>
  2581.                         <body>
  2582.                         <div class="pai">';
  2583.         
  2584.                 $count 0;
  2585.         
  2586.                 
  2587.                         foreach ($fluxo_caixas as $caixa) {
  2588.                             $count++;
  2589.                             $documento_fluxo $caixa->getDocumentos()->toArray();
  2590.                             
  2591.                 
  2592.                             $html .= '<div class="filho">
  2593.                                 
  2594.                                 
  2595.                                 <h6><img src="'.$cliente_all_Url.'" class="img"></h6>
  2596.                                 <hr>
  2597.                                 <h2>' htmlspecialchars($caixa->getNome()) . '</h2>
  2598.                                 <hr>
  2599.                                 ';
  2600.                 
  2601.                             $docs = [];
  2602.                             
  2603.                             if (!empty($documento_fluxo)) {
  2604.                                 foreach ($documento_fluxo as $doc) {
  2605.                                     if($doc->getTipo() != NULL ){
  2606.                                         if ($cliente_id != 122) {
  2607.                                             $docs[] = $doc->getTipo()->getNome();
  2608.                                         } else {
  2609.                                             $docs[] = $doc->getNome();
  2610.                                         }
  2611.                                     }
  2612.                                 }
  2613.                                 $docs array_unique($docs);
  2614.                             }
  2615.                             
  2616.                             
  2617.                             $docs_class = [];
  2618.                             
  2619.                             if (!empty($documento_fluxo)) {
  2620.                                 foreach ($documento_fluxo as $doc) {
  2621.                                     
  2622.                                     if($doc->getClassificacao() != NULL ){
  2623.                                        $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  2624.                                        $class_nome =  $clss[0]->getNome();
  2625.                                        $docs_class[] = $class_nome;
  2626.                                         
  2627.                                     }
  2628.                                 }
  2629.                                 $docs_class array_unique($docs_class);
  2630.                             }
  2631.                 
  2632.                               $docs_data = [];
  2633.                               if (!empty($documento_fluxo)) {
  2634.                                     foreach ($documento_fluxo as $data) {
  2635.                                         if ($data->getAssunto() !== null) {
  2636.                                             $docs_data[] = $data->getAssunto();
  2637.                                         }
  2638.                                     }
  2639.                                     $docs_data array_unique($docs_data);
  2640.                                 }
  2641.                             
  2642.                           
  2643.                             
  2644.                                                         
  2645.                             
  2646.                             
  2647.                             $html .= '<h6>' htmlspecialchars(implode(', '$docs)) . '</h6>
  2648.                                 <hr>';
  2649.                                
  2650.                                 $html .= '<h6>Conteúdo:</h6>';
  2651.                                 $html .= '<div class="lis">';
  2652.                                 foreach ($docs_class as $classs_nome) {
  2653.                                 if($classs_nome == '028.11-COM ÔNUS'){
  2654.                                  $html .= '<li>SOLICITAÇÃO DE DIÁRIAS</li>';
  2655.                                 }
  2656.                                 $html .= '
  2657.                                     <li>' $classs_nome'</li>';
  2658.                                 }
  2659.                                 $html .= '</div><br>';
  2660.                                 $html .= '<h6>Descrição:</h6>';
  2661.                                 $html .= '<div class="lis">';
  2662.                                 $len count($docs_data);
  2663.                                 foreach ($docs_data as $assunto_nome) {
  2664.                                     
  2665.                                 $qtd_letra mb_strlen($assunto_nome'UTF-8');
  2666.                                  
  2667.                                 if ($len <= 20) {
  2668.                                     $fontSize 12;
  2669.                                 } 
  2670.                                 
  2671.                                 else{
  2672.                                     $fontSize 9;
  2673.                                 }
  2674.                                 if($qtd_letra 25 ){
  2675.                                     $fontSize 10;
  2676.                                 }
  2677.                                 $html .= '<li style="font-size: ' $fontSize 'px;">' $assunto_nome'</li>';
  2678.                                 }
  2679.                                 $html .= '</div><br>
  2680.                                 <div class="lis3"><hr>
  2681.                                 
  2682.                                 <p>ARQUIVOS GESTÃO DOCUMENTAL</p>
  2683.                                 <h5><img src="https://index.arquivosdoc.com.br/img/logo_menu.png" class="img"></h5>
  2684.                                 </div>
  2685.                                 
  2686.                             </div>';
  2687.                 
  2688.                             #if ($count == 4) {
  2689.                              #   $html .= '<div style="page-break-after: always;"></div>';
  2690.                             #}
  2691.                         }
  2692.                
  2693.                 
  2694.                 
  2695.         
  2696.                 $html .= '</div></body></html>';
  2697.         
  2698.   
  2699.                         
  2700.                
  2701.                
  2702.                 // Configurar o Dompdf
  2703.                 $options = new Options();
  2704.                 $options->set('isHtml5ParserEnabled'true);
  2705.                 $options->set('isPhpEnabled'true);
  2706.                 $options->set('isRemoteEnabled'true);
  2707.                 $dompdf = new Dompdf($options);
  2708.                 $dompdf->loadHtml($html);
  2709.                 $dompdf->setPaper('A4''portrait');
  2710.         
  2711.                 // LIMPA TODOS OS BUFFERS ANTES DE RENDERIZAR
  2712.                 while (ob_get_level()) {
  2713.                     ob_end_clean();
  2714.                 }
  2715.         
  2716.                 // Tenta renderizar e, em vez de stream() direto, grava em arquivo temporário e envia
  2717.                 try {
  2718.                     $dompdf->render();
  2719.                 } catch (Throwable $e) {
  2720.                     // registra o erro e lança para cair no catch externo
  2721.                     error_log('Dompdf render failed: ' $e->getMessage());
  2722.                     throw $e;
  2723.                 }
  2724.         
  2725.                 // Gera arquivo temporário seguro
  2726.                 $tempFile sys_get_temp_dir() . DIRECTORY_SEPARATOR 'etiqueta_fluxo_' $id_fluxo '_' uniqid() . '.pdf';
  2727.                 $output $dompdf->output();
  2728.         
  2729.                 if (file_put_contents($tempFile$output) === false) {
  2730.                     throw new Exception('Falha ao escrever arquivo temporário do PDF.');
  2731.                 }
  2732.         
  2733.                 // Força headers corretos para download/visualização
  2734.                 header('Content-Type: application/pdf');
  2735.                 // Se quiser forçar download use attachment; se quiser abrir no browser use inline
  2736.                 header('Content-Disposition: inline; filename="Etiqueta_Fluxo_' preg_replace('/[^A-Za-z0-9_\-\.]/''_'$id_fluxo '_' $nome_fluxo) . '.pdf"');
  2737.                 header('Content-Length: ' filesize($tempFile));
  2738.                 header('Cache-Control: private, max-age=0, must-revalidate');
  2739.         
  2740.                 // Envia o arquivo binário ao navegador
  2741.                 readfile($tempFile);
  2742.         
  2743.                 // Remove o arquivo temporário com segurança
  2744.                 @unlink($tempFile);
  2745.         
  2746.                 // finaliza execução
  2747.                 exit;
  2748.         
  2749.                 
  2750.        
  2751.         
  2752.         }
  2753.        
  2754.         
  2755.        
  2756.        
  2757.         return $this->render('index/index5.html.twig', [
  2758.     
  2759.             'fluxos' => $fluxos,
  2760.             'p'=>$p,
  2761.             'erro'=>$erro,
  2762.             'pagina' => $pagina,
  2763.             'a' => $a,
  2764.              
  2765.         ]);
  2766.     }
  2767.     
  2768.     
  2769.     #[Route('/index/fluxo/diagrama/{id}'name'diagrama')]
  2770.     public function diagramaPaginatorInterface $paginator,Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer,$id): Response
  2771.     {
  2772.         $user_logado $this->getUser();
  2773.         $erro '';
  2774.         $pagina 'fluxo';
  2775.         $p ='';
  2776.         $clienteId $session->get('cliente_id');
  2777.         
  2778.         if($clienteId == null){
  2779.             
  2780.             return $this->redirectToRoute('home');
  2781.         }
  2782.         
  2783.         $fluxo_diagrama $doctrine->getRepository(Fluxo::class)->find($id);
  2784.         $fluxo_caixas_diagrama $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_diagrama->getId());
  2785.             
  2786.  
  2787.     
  2788.         return $this->render('index/diagrama.html.twig', [
  2789.     
  2790.             'p'=>$p,
  2791.             'erro'=>$erro,
  2792.             'pagina' => $pagina,
  2793.             "fluxo_diagrama" => $fluxo_diagrama,
  2794.             "fluxo_caixas_diagrama" => $fluxo_caixas_diagrama
  2795.              
  2796.         ]);
  2797.     }
  2798.     #[Route('/index/recebimento/{id}'name'recebimento')]
  2799.     public function recebimentoPaginatorInterface $paginator,Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer,$id): Response
  2800.     {
  2801.         $user_logado $this->getUser();
  2802.         $user_nome $user_logado->getNome();
  2803.         $ip_cliente $_SERVER['REMOTE_ADDR'];
  2804.         $erro '';
  2805.         $pagina 'home';
  2806.         $p ='';
  2807.         $ged ""
  2808.         $log "";
  2809.         $caixa_manual "";
  2810.         $caixa_auto "";
  2811.         $cx_ultimo $doctrine->getRepository(Cx::class)->findUltimo();
  2812.         $etapa $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  2813.         $fluxo $etapa->getFluxo();
  2814.         $cliente_fluxo $fluxo->getCliente()->getId();
  2815.         $clienteId $session->get('cliente_id');
  2816.         $cliente $doctrine->getRepository(Cliente::class)->findWithRelations($cliente_fluxo);
  2817.         $clienteAll =  $cliente->getClienteAll();
  2818.         $cliente_nome =  $cliente->getNome();
  2819.         $clienteAll_id =  $clienteAll->getId();
  2820.         $count 0// Contador de QR Codes
  2821.         $id_cx_ultimo 0;
  2822.         $date_hoje = new \DateTimeImmutable('America/Sao_Paulo');
  2823.         
  2824.         $caixas_setor $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($cliente_fluxo);
  2825.         
  2826.         $query $entityManager->createQuery("
  2827.             SELECT c FROM App\Entity\Cx c
  2828.             LEFT JOIN c.caixas cx
  2829.             WHERE c.cliente = :clienteId
  2830.             AND cx.id IS NULL
  2831.         ");
  2832.         $query->setParameter('clienteId'$clienteAll_id);
  2833.         $cx_setor $query->getResult();
  2834.         foreach ($cx_ultimo as $key_id) {
  2835.             
  2836.             $id_cx_ultimo $key_id->getNome();
  2837.         }
  2838.         
  2839.         if(isset($_POST["btn_cliente"])){
  2840.             
  2841.             $session->set('cliente_id'$_POST["btn_cliente"]);
  2842.             return $this->redirectToRoute('home');
  2843.         }
  2844.         
  2845.         if($clienteId == null){
  2846.             
  2847.             return $this->redirectToRoute('home');
  2848.         }
  2849.         
  2850.         if ($request->isMethod('POST')) {
  2851.             
  2852.           
  2853.             
  2854.             if(isset($_POST["tipo"])){
  2855.                  $tp $_POST["tipo"];
  2856.                
  2857.                if($tp =='caixa'){
  2858.                    
  2859.                     if($_POST["qtd_caixa"] != ""){
  2860.     
  2861.     
  2862.                         if (isset($_POST["ged"]) || isset($_POST["log"])) {
  2863.     
  2864.                                 if (isset($_POST["ged"])) {
  2865.                                     
  2866.                                     $ged "ok";
  2867.     
  2868.                                     if (isset($_POST["caixa_manual"]) || isset($_POST["caixa_auto"])) {
  2869.     
  2870.                                         if (isset($_POST["caixa_manual"])) {
  2871.     
  2872.                                             $caixa_manual "ok";
  2873.             
  2874.                                         }
  2875.                                         if (isset($_POST["caixa_auto"])) {
  2876.     
  2877.                                             $caixa_auto "ok";
  2878.             
  2879.                                         }
  2880.     
  2881.                                     }else{
  2882.                                         echo "<script>alert('ERROR , Selecione o modo de Identificação do ArquivosGED (Manual ou Automático)!');</script>";
  2883.                                     }
  2884.             
  2885.                                 }
  2886.     
  2887.     
  2888.     
  2889.                                 if (isset($_POST["log"])) {
  2890.     
  2891.                                     $log "ok";
  2892.                                     
  2893.     
  2894.                                 }
  2895.     
  2896.                                 if ($ged == "ok" and $caixa_manual =="ok") {
  2897.     
  2898.                                     $caixa $_POST["caixa"];
  2899.                                     $qtd_caixas 0;
  2900.     
  2901.     
  2902.                                     $options = new Options();
  2903.                                     $options->set('isHtml5ParserEnabled'true);
  2904.                                     $options->set('isPhpEnabled'true);
  2905.                                     $dompdf = new Dompdf($options);
  2906.                         
  2907.                                     $html '
  2908.                                     <html>
  2909.                                         <head>
  2910.                                             <style>
  2911.                                                 @page {
  2912.                                                     margin: 35px 18.9px 0px 18.9px;
  2913.                                                     size: 210mm 297mm; /* Ajuste de tamanho do papel */
  2914.                                                 }
  2915.                         
  2916.                                                 body {
  2917.                                                     margin: 0;
  2918.                                                     padding: 0;
  2919.                                                 }
  2920.                                                 
  2921.                                                 .qr-item {
  2922.                                                     border: 2px dotted #000;
  2923.                                                     text-align: center;
  2924.                                                     width: 32.27mm;
  2925.                                                     height: 34.9mm; 
  2926.                                                     display: inline-block;
  2927.                                                 }
  2928.                                     
  2929.                                                 .qr-item img {
  2930.                                                     width: 115px; 
  2931.                                                     height: 112px;
  2932.                                                 }
  2933.                         
  2934.                                                 .qr-title {
  2935.                                                     font-size: 16px;
  2936.                                                     font-weight: bold;
  2937.                                                 }
  2938.                         
  2939.                                                 .leo {
  2940.                                                     display: flex;
  2941.                                                     flex-wrap: wrap;
  2942.                                                 }
  2943.                                             </style>
  2944.                                         </head>
  2945.                                         <body> 
  2946.                                       
  2947.                                     ';
  2948.                         
  2949.                         
  2950.                                     
  2951.                                     foreach ($caixa as $key) {
  2952.     
  2953.                                         if ($key != "" ) {
  2954.                                             $qtd_caixas ++ ;
  2955.                                             $caixas = new Caixa();
  2956.                                            
  2957.                                            
  2958.                                             if ($ged == "ok" and $log =="ok") {
  2959.                                                 
  2960.                                                 $cx = new Cx();
  2961.                                                 $id_cx_ultimo ++;
  2962.                                                 $cx->setNome($id_cx_ultimo);
  2963.                                                 $cx->setStatus(2);
  2964.                                                 $cx->setTexto($key);
  2965.                                                 $cx->setImage('ArquivosGED');
  2966.                                                 $cx->setCliente($clienteAll);
  2967.                                                 $entityManager->persist($cx);
  2968.                                                 $entityManager->flush();
  2969.     
  2970.                                                 $id_cx=$cx->getId();
  2971.                                                 $caixas->setCx($entityManager->getRepository(Cx::class)->find($id_cx));
  2972.     
  2973.                                                 // Gerar QR Code com imagem no centro
  2974.                                                 $result Builder::create()
  2975.                                                 ->writer(new PngWriter())
  2976.                                                 ->writerOptions([])
  2977.                                                 ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  2978.                                                 ->encoding(new Encoding('UTF-8'))
  2979.                                                 ->size(500)
  2980.                                                 ->margin(5)
  2981.                                                 ->logoPath(__DIR__ '/logo.png'// Caminho do logo central
  2982.                                                 ->build();
  2983.                                                 // Salvar QR Code como arquivo temporário
  2984.                                                 $tempFile tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  2985.                                                 $result->saveToFile($tempFile);
  2986.                                                 
  2987.                                                 // Adicionar QR Code ao HTML
  2988.                                                 if ($count 48 == 0) {
  2989.                                                     $html .= '<div class="leo">';
  2990.                                                 }
  2991.                                 
  2992.                                                 // Adicionar QR Code ao HTML
  2993.                                                 $html .= '<div class="qr-item">';
  2994.                                                 $html .= '<div class="qr-title">' $id_cx_ultimo '</div>';
  2995.                                                 $html .= '<img src="data:image/png;base64,' base64_encode(file_get_contents($tempFile)) . '">';
  2996.                                                 $html .= '</div>';
  2997.                                                 
  2998.                                                 
  2999.                                                  $count++;
  3000.     
  3001.                                                // Fechar a div e inserir quebra de página a cada 63 QR Codes
  3002.                                                if ($count 48 == 0) {
  3003.                                                    $html .= '</div><div style="page-break-after: always;"></div>';
  3004.                                                }
  3005.                                                 
  3006.                                             }
  3007.     
  3008.                                             
  3009.                                             $caixas->setNome($key);
  3010.                                             $caixas->addCliente($cliente);
  3011.                                             $caixas->setFluxo($fluxo);
  3012.                                             $entityManager->persist($caixas);
  3013.                                             $entityManager->flush();
  3014.                                             $id_caixa $caixas->getId();
  3015.                                             
  3016.                                                 
  3017.                                         }
  3018.                                     }
  3019.                                         if ($ged == "ok" and $log =="ok") {
  3020.                                             
  3021.                                               // Fechar qualquer div aberta sem completar 63 itens
  3022.                                              if ($count 48 != 0) {
  3023.                                                 $html .= '</div>';
  3024.                                             }
  3025.     
  3026.                                             $html .= '</div></body></html>';
  3027.                                 
  3028.                                             // Carregar o HTML e gerar o PDF
  3029.                                             $dompdf->loadHtml($html);
  3030.                                             $dompdf->setPaper([00210297], 'portrait'); // Configurar o tamanho de página para A4
  3031.                                             $dompdf->render();
  3032.                                             #file_put_contents('sample1.pdf', $dompdf->output());
  3033.                                             $dompdf->stream('dompdf', array('Attachment' => 0));
  3034.                                         }
  3035.     
  3036.                                             $registro = new Registro();
  3037.                                             $registro->setOperacao('RECEBIMENTO DE '.$qtd_caixas' CAIXA(S)'); 
  3038.                                             $registro->setUser($user_nome);
  3039.                                             $registro->setCliente($cliente_nome);
  3040.                                             $registro->setIp($ip_cliente);
  3041.                                             $entityManager->persist($registro);
  3042.                                             $entityManager->flush();
  3043.     
  3044.                                             $etapa->setRegistro($registro);
  3045.                                             $etapa->setObs($_POST["obs_caixa"]);
  3046.                                             $etapa->setUpdatedAt($date_hoje);
  3047.                                             $entityManager->flush();
  3048.                                             $erro 'ok';
  3049.                                             $p "Recbimento com sucesso";
  3050.                                     
  3051.     
  3052.                                 }
  3053.     
  3054.                                 if ($ged == "ok" and $caixa_auto =="ok") {
  3055.     
  3056.                                     
  3057.                                     if (isset($_POST["auto_ged"])) {
  3058.     
  3059.                                         $qtd_nome_caixa $_POST["qtd_caixa"];
  3060.                                         $nome_caixa_parti $_POST["auto_ged"];
  3061.                                         
  3062.     
  3063.     
  3064.     
  3065.                                         $options = new Options();
  3066.                                         $options->set('isHtml5ParserEnabled'true);
  3067.                                         $options->set('isPhpEnabled'true);
  3068.                                         $dompdf = new Dompdf($options);
  3069.                             
  3070.                                         $html '
  3071.                                         <html>
  3072.                                             <head>
  3073.                                                 <style>
  3074.                                                     @page {
  3075.                                                         margin: 35px 18.9px 0px 18.9px;
  3076.                                                         size: 210mm 297mm; /* Ajuste de tamanho do papel */
  3077.                                                     }
  3078.                             
  3079.                                                     body {
  3080.                                                         margin: 0;
  3081.                                                         padding: 0;
  3082.                                                     }
  3083.                                                     
  3084.                                                    .qr-item {
  3085.                                                     border: 2px dotted #000;
  3086.                                                     text-align: center;
  3087.                                                     width: 32.27mm;
  3088.                                                     height: 34.9mm; 
  3089.                                                     display: inline-block;
  3090.                                                 }
  3091.                                     
  3092.                                                 .qr-item img {
  3093.                                                     width: 115px; 
  3094.                                                     height: 112px;
  3095.                                                 }
  3096.                                     
  3097.                                                     .qr-title {
  3098.                                                         font-size: 16px;
  3099.                                                         font-weight: bold;
  3100.                                                     }
  3101.                             
  3102.                                                     .leo {
  3103.                                                         display: flex;
  3104.                                                         flex-wrap: wrap;
  3105.                                                     }
  3106.                                                 </style>
  3107.                                             </head>
  3108.                                             <body> 
  3109.                                               
  3110.                                         ';
  3111.                         
  3112.                         
  3113.     
  3114.     
  3115.                                         for ($i=0$i $qtd_nome_caixa$i++) { 
  3116.                                             
  3117.                                             $caixas = new Caixa();
  3118.     
  3119.                                             if ($ged == "ok" and $log =="ok") {
  3120.                                                 
  3121.                                                 $cx = new Cx();
  3122.                                                 $id_cx_ultimo ++;
  3123.                                                 $cx->setNome($id_cx_ultimo);
  3124.                                                 $cx->setStatus(2);
  3125.                                                 $cx->setTexto('Caixa '.$nome_caixa_parti);
  3126.                                                 $cx->setImage('ArquivosGED');
  3127.                                                 $cx->setCliente($clienteAll);
  3128.                                                 $entityManager->persist($cx);
  3129.                                                 $entityManager->flush();
  3130.     
  3131.                                                 $id_cx=$cx->getId();
  3132.                                                 $caixas->setCx($entityManager->getRepository(Cx::class)->find($id_cx));
  3133.     
  3134.                                                   // Gerar QR Code com imagem no centro
  3135.                                                 $result Builder::create()
  3136.                                                   ->writer(new PngWriter())
  3137.                                                   ->writerOptions([])
  3138.                                                   ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  3139.                                                   ->encoding(new Encoding('UTF-8'))
  3140.                                                   ->size(500)
  3141.                                                   ->margin(5)
  3142.                                                   ->logoPath(__DIR__ '/logo.png'// Caminho do logo central
  3143.                                                   ->build();
  3144.                                                   // Salvar QR Code como arquivo temporário
  3145.                                                   $tempFile tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  3146.                                                   $result->saveToFile($tempFile);
  3147.                                                     
  3148.                                                 // Adicionar QR Code ao HTML
  3149.                                                     if ($count 48 == 0) {
  3150.                                                         $html .= '<div class="leo">';
  3151.                                                     }    
  3152.                                                     
  3153.                                                   // Adicionar QR Code ao HTML
  3154.                                                   $html .= '<div class="qr-item">';
  3155.                                                   $html .= '<div class="qr-title">' $id_cx_ultimo '</div>';
  3156.                                                   $html .= '<img src="data:image/png;base64,' base64_encode(file_get_contents($tempFile)) . '">';
  3157.                                                   $html .= '</div>';
  3158.                                                   
  3159.                                                    $count++;
  3160.                                         
  3161.                                                    // Fechar a div e inserir quebra de página a cada 63 QR Codes
  3162.                                                    if ($count 48 == 0) {
  3163.                                                        $html .= '</div><div style="page-break-after: always;"></div>';
  3164.                                                    }
  3165.                                                 
  3166.                                             }
  3167.     
  3168.     
  3169.                                             $caixas->setNome('Caixa '.$nome_caixa_parti);
  3170.                                             $caixas->addCliente($cliente);
  3171.                                             $caixas->setFluxo($fluxo);
  3172.                                             $entityManager->persist($caixas);
  3173.                                             $entityManager->flush();
  3174.                                             $nome_caixa_parti++;
  3175.                                             
  3176.     
  3177.                                         }
  3178.     
  3179.                                         if ($ged == "ok" and $log =="ok") {
  3180.                                     
  3181.                                              // Fechar qualquer div aberta sem completar 63 itens
  3182.                                              if ($count 48 != 0) {
  3183.                                                 $html .= '</div>';
  3184.                                             }
  3185.                                             
  3186.                                             $html .= '</div></body></html>';
  3187.                                     
  3188.                                             // Carregar o HTML e gerar o PDF
  3189.                                             $dompdf->loadHtml($html);
  3190.                                             $dompdf->setPaper([00210297], 'portrait'); // Configurar o tamanho de página para A4
  3191.                                             $dompdf->render();
  3192.                                             #file_put_contents('sample1.pdf', $dompdf->output());
  3193.                                             $dompdf->stream('dompdf', array('Attachment' => 0));
  3194.                                         }    
  3195.     
  3196.                                         $registro = new Registro();
  3197.                                         $registro->setOperacao('RECEBIMENTO DE '.$qtd_nome_caixa' CAIXA(S)'); 
  3198.                                         $registro->setUser($user_nome);
  3199.                                         $registro->setCliente($cliente_nome);
  3200.                                         $registro->setIp($ip_cliente);
  3201.                                         $entityManager->persist($registro);
  3202.                                         $entityManager->flush();
  3203.                                         
  3204.                                         $etapa->setUpdatedAt($date_hoje);
  3205.                                         $etapa->setRegistro($registro);
  3206.                                         $entityManager->flush();
  3207.     
  3208.                                         $erro 'ok';
  3209.                                         $p "Recbimento com sucesso";
  3210.                                         
  3211.                                     }
  3212.     
  3213.                                 }
  3214.     
  3215.     
  3216.     
  3217.                                 if ($ged != "ok" and $log =="ok") {
  3218.                                     
  3219.                                     $qtd_caixa_ $_POST["qtd_caixa"];
  3220.                                     $options = new Options();
  3221.                                     $options->set('isHtml5ParserEnabled'true);
  3222.                                     $options->set('isPhpEnabled'true);
  3223.                                     $dompdf = new Dompdf($options);
  3224.                             
  3225.                                         $html '
  3226.                                         <html>
  3227.                                             <head>
  3228.                                                 <style>
  3229.                                                     @page {
  3230.                                                         margin: 35px 18.9px 0px 18.9px;
  3231.                                                         size: 210mm 297mm; /* Ajuste de tamanho do papel */
  3232.                                                     }
  3233.                             
  3234.                                                     body {
  3235.                                                         margin: 0;
  3236.                                                         padding: 0;
  3237.                                                     }
  3238.                                                     
  3239.                                                     .qr-item {
  3240.                                                         border: 2px dotted #000;
  3241.                                                         text-align: center;
  3242.                                                         width: 27.5mm;
  3243.                                                         height: 30.5mm; 
  3244.                                                         display: inline-block;
  3245.                                                     }
  3246.                             
  3247.                                                     .qr-item img {
  3248.                                                         width: 105px; 
  3249.                                                         height: 100px;
  3250.                                                     }
  3251.                             
  3252.                                                     .qr-title {
  3253.                                                         font-size: 16px;
  3254.                                                         font-weight: bold;
  3255.                                                     }
  3256.                             
  3257.                                                     .leo {
  3258.                                                         display: flex;
  3259.                                                         flex-wrap: wrap;
  3260.                                                     }
  3261.                                                 </style>
  3262.                                             </head>
  3263.                                             <body> 
  3264.                                                 <div class="leo">    
  3265.                                         ';
  3266.     
  3267.     
  3268.     
  3269.                                     for ($i=0$i $qtd_caixa_$i++) { 
  3270.                                             
  3271.                                                 $id_cx_ultimo ++;
  3272.                                                 // Gerar QR Code com imagem no centro
  3273.                                             $result Builder::create()
  3274.                                                 ->writer(new PngWriter())
  3275.                                                 ->writerOptions([])
  3276.                                                 ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  3277.                                                 ->encoding(new Encoding('UTF-8'))
  3278.                                                 ->size(300)
  3279.                                                 ->margin(10)
  3280.                                                 ->logoPath(__DIR__ '/logo.png'// Caminho do logo central
  3281.                                                 ->build();
  3282.                                                 // Salvar QR Code como arquivo temporário
  3283.                                                 $tempFile tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  3284.                                                 $result->saveToFile($tempFile);
  3285.                                 
  3286.                                                 // Adicionar QR Code ao HTML
  3287.                                                 $html .= '<div class="qr-item">';
  3288.                                                 $html .= '<div class="qr-title">' $id_cx_ultimo '</div>';
  3289.                                                 $html .= '<img src="data:image/png;base64,' base64_encode(file_get_contents($tempFile)) . '">';
  3290.                                                 $html .= '</div>';
  3291.                                     }
  3292.                                     
  3293.                                     $html .= '</div></body></html>';
  3294.                             
  3295.                                     // Carregar o HTML e gerar o PDF
  3296.                                     $dompdf->loadHtml($html);
  3297.                                     $dompdf->setPaper([00210297], 'portrait'); // Configurar o tamanho de página para A4
  3298.                                     $dompdf->render();
  3299.                                     file_put_contents('sample1.pdf'$dompdf->output());
  3300.                                     $dompdf->stream('dompdf', array('Attachment' => 1));
  3301.     
  3302.     
  3303.                                     $registro = new Registro();
  3304.                                     $registro->setOperacao('RECEBIMENTO DE '.$qtd_caixa_' CAIXA(S)'); 
  3305.                                     $registro->setUser($user_nome);
  3306.                                     $registro->setCliente($cliente_nome);
  3307.                                     $registro->setIp($ip_cliente);
  3308.                                     $entityManager->persist($registro);
  3309.                                     $entityManager->flush();
  3310.                                     
  3311.                                     $etapa->setUpdatedAt($date_hoje);
  3312.                                     $etapa->setRegistro($registro);
  3313.                                     $entityManager->flush();
  3314.     
  3315.                                     $erro 'ok';
  3316.                                     $p "Recbimento com sucesso";
  3317.     
  3318.     
  3319.                                 }
  3320.     
  3321.     
  3322.     
  3323.     
  3324.                             } else {
  3325.     
  3326.                             echo "<script>alert('ERROR , Selecione a Identificação!');</script>";
  3327.                         }
  3328.                          
  3329.                     }else {
  3330.                         echo "<script>alert('ERROR , Selecione a Quantidade!');</script>";
  3331.                     }
  3332.                }
  3333.                
  3334.                 if($tp =='doc'){
  3335.                     if(isset($_POST["check_cx_e"])){
  3336.                         $yz "yes";
  3337.                         $checkBoxes $request->request->all('inputs_cx_e');
  3338.                         $xy 0;
  3339.                         $qtd_caixas=0;
  3340.                         
  3341.       
  3342.                         foreach ($checkBoxes as $id => $nome) {
  3343.                             $cx_ $doctrine->getRepository(Cx::class)->find($id);
  3344.                             $_nome =  $cx_->getNome();
  3345.                            
  3346.                             if ($nome =="") {
  3347.                                
  3348.                                 echo "<script>alert('ERROR, Digite no campo gerado acima da tabela qual será repositorio do  ID: $_nome!');</script>";
  3349.                             }
  3350.                             if ($nome != "" ) {
  3351.                                 $id_cx_ultimo $_nome ;
  3352.                                 $qtd_caixas++;
  3353.                                 $xy 1;
  3354.                                 $caixas = new Caixa();
  3355.                                 $caixas->setNome($nome);
  3356.                                 $caixas->addCliente($cliente);
  3357.                                 $caixas->setFluxo($fluxo);
  3358.                                 $caixas->setCx($cx_);
  3359.                                 $entityManager->persist($caixas);
  3360.                                 $entityManager->flush();
  3361.                                 $registro = new Registro();
  3362.                                 $registro->setOperacao('RECEBIMENTO DA ID EXISTENTE '.$_nome); 
  3363.                                 $registro->setUser($user_nome);
  3364.                                 $registro->setCliente($cliente_nome);
  3365.                                 $registro->setIp($ip_cliente);
  3366.                                 $entityManager->persist($registro);
  3367.                                 $entityManager->flush();
  3368.                                 
  3369.                                 
  3370.                                 
  3371.                             }
  3372.                             
  3373.                         }
  3374.                        
  3375.                         if($xy==1){
  3376.                             $etapa->setRegistro($registro);
  3377.                             $etapa->setObs($_POST["obs_caixa"]);
  3378.                             $etapa->setUpdatedAt($date_hoje);
  3379.                             $entityManager->flush();
  3380.                             
  3381.                             $registro = new Registro();
  3382.                             $registro->setOperacao('RECEBIMENTO DE  '.$qtd_caixas' CAIXA(S) '); 
  3383.                             $registro->setUser($user_nome);
  3384.                             $registro->setCliente($cliente_nome);
  3385.                             $registro->setIp($ip_cliente);
  3386.                             $entityManager->persist($registro);
  3387.                             $entityManager->flush();
  3388.                             $erro 'ok';
  3389.                             $p "Recbimento com sucesso";
  3390.                         }
  3391.                       
  3392.                     }else{
  3393.                         $zy "not";
  3394.                     }
  3395.                     if(isset($_POST["check_caixa_e"])){
  3396.                         $zy "yes";
  3397.                         $options = new Options();
  3398.                         $options->set('isHtml5ParserEnabled'true);
  3399.                         $options->set('debugKeepTemp'true);
  3400.                         $options->set('isPhpEnabled'true);
  3401.                         $dompdf = new Dompdf($options);
  3402.                         
  3403.                         $html '
  3404.                                     <html>
  3405.                                         <head>
  3406.                                             <style>
  3407.                                                 @page {
  3408.                                                     margin: 35px 18.9px 0px 18.9px;
  3409.                                                     size: 210mm 297mm; /* Ajuste de tamanho do papel */
  3410.                                                 }
  3411.                         
  3412.                                                 body {
  3413.                                                     margin: 0;
  3414.                                                     padding: 0;
  3415.                                                 }
  3416.                                                 
  3417.                                                 .qr-item {
  3418.                                                     border: 2px dotted #000;
  3419.                                                     text-align: center;
  3420.                                                     width: 32.27mm;
  3421.                                                     height: 34.9mm; 
  3422.                                                     display: inline-block;
  3423.                                                 }
  3424.                                     
  3425.                                                 .qr-item img {
  3426.                                                     width: 115px; 
  3427.                                                     height: 112px;
  3428.                                                 }
  3429.                         
  3430.                                                 .qr-title {
  3431.                                                     font-size: 16px;
  3432.                                                     font-weight: bold;
  3433.                                                 }
  3434.                         
  3435.                                                 .leo {
  3436.                                                     display: flex;
  3437.                                                     flex-wrap: wrap;
  3438.                                                 }
  3439.                                             </style>
  3440.                                         </head>
  3441.                                         <body> 
  3442.                                     
  3443.                                     ';
  3444.                         
  3445.                         $ckeck $_POST["caixa_e"];
  3446.                         $xy 0;
  3447.                         $qtd_caixas=0;
  3448.                 
  3449.                         foreach ($ckeck as $key) {
  3450.                             $nome_k NULL;
  3451.                             $caixa_k $doctrine->getRepository(Caixa::class)->find($key);
  3452.                             if($caixa_k != NULL ){
  3453.                                 $nome_k $caixa_k->getNome();
  3454.                             }
  3455.                             
  3456.                             if ($clienteAll_id != 18) {
  3457.                             
  3458.                                 $cx = new Cx();
  3459.                                 $id_cx_ultimo ++;
  3460.                                 $cx->setNome($id_cx_ultimo);
  3461.                                 $cx->setStatus(2);
  3462.                                 $cx->setTexto($nome_k);
  3463.                                 $cx->setImage('ArquivosGED');
  3464.                                 $cx->setCliente($clienteAll);
  3465.                                 $entityManager->persist($cx);
  3466.                                 $entityManager->flush();
  3467.                                 $caixa_k->setCx($cx);
  3468.                                 
  3469.                             }
  3470.                             
  3471.                             $caixa_k->setFluxo($fluxo);
  3472.                             $entityManager->flush();
  3473.                             $registro = new Registro();
  3474.                             $registro->setOperacao('RECEBIMENTO DA CAIXA EXISTENTE '.$nome_k); 
  3475.                             $registro->setUser($user_nome);
  3476.                             $registro->setCliente($cliente_nome);
  3477.                             $registro->setIp($ip_cliente);
  3478.                             $entityManager->persist($registro);
  3479.                             $entityManager->flush();
  3480.                             // Gerar QR Code com imagem no centro
  3481.                             $result Builder::create()
  3482.                              ->writer(new PngWriter())
  3483.                              ->writerOptions([])
  3484.                              ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  3485.                              ->encoding(new Encoding('UTF-8'))
  3486.                              ->size(500)
  3487.                              ->margin(5)
  3488.                              ->logoPath(__DIR__ '/logo.png'// Caminho do logo central
  3489.                              ->build();
  3490.                              // Salvar QR Code como arquivo temporário
  3491.                              $tempFile tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  3492.                              $result->saveToFile($tempFile);
  3493.                              
  3494.                              // Adicionar QR Code ao HTML
  3495.                              if ($count 48 == 0) {
  3496.                                  $html .= '<div class="leo">';
  3497.                              }
  3498.              
  3499.                              // Adicionar QR Code ao HTML
  3500.                              $html .= '<div class="qr-item">';
  3501.                              $html .= '<div class="qr-title">' $id_cx_ultimo '</div>';
  3502.                              $html .= '<img src="data:image/png;base64,' base64_encode(file_get_contents($tempFile)) . '">';
  3503.                              $html .= '</div>';
  3504.                              
  3505.                              
  3506.                              $count++;
  3507.                             // Fechar a div e inserir quebra de página a cada 63 QR Codes
  3508.                             if ($count 48 == 0) {
  3509.                                 $html .= '</div><div style="page-break-after: always;"></div>';
  3510.                             }
  3511.                              
  3512.                             
  3513.                         }
  3514.                         // Fechar qualquer div aberta sem completar 63 itens
  3515.                         if ($count 48 != 0) {
  3516.                             $html .= '</div>';
  3517.                         }
  3518.                          
  3519.                         $html .= '</div></body></html>';
  3520.                         
  3521.                         if ($clienteAll_id != 18) {  
  3522.                             // Carregar o HTML e gerar o PDF
  3523.                             $dompdf->loadHtml($html);
  3524.                             $dompdf->setPaper([00210297], 'portrait'); // Configurar o tamanho de página para A4
  3525.                             $dompdf->render();
  3526.                             #file_put_contents('sample1.pdf', $dompdf->output());
  3527.                             $dompdf->stream('dompdf', array('Attachment' => 0));
  3528.                         }
  3529.                         if($xy==1){
  3530.                             $etapa->setRegistro($registro);
  3531.                             $etapa->setUpdatedAt($date_hoje);
  3532.                             $etapa->setObs($_POST["obs_caixa"]);
  3533.                             $entityManager->flush();
  3534.                             
  3535.                             $registro = new Registro();
  3536.                             $registro->setOperacao('RECEBIMENTO DE  '.$qtd_caixas' CAIXA(S) '); 
  3537.                             $registro->setUser($user_nome);
  3538.                             $registro->setCliente($cliente_nome);
  3539.                             $registro->setIp($ip_cliente);
  3540.                             $entityManager->persist($registro);
  3541.                             $entityManager->flush();
  3542.                             $erro 'ok';
  3543.                             $p "Recbimento com sucesso";
  3544.                         }
  3545.                       
  3546.                     }else{
  3547.                         $yz "not";
  3548.                     }
  3549.                     if ($yz == "not" and $zy="not") {
  3550.                         echo "<script>alert('ERROR , Preencha corretamente o formulario, está sem valor , selecione todas as opções necessaria!');</script>";
  3551.                     }
  3552.                    
  3553.                 }
  3554.                
  3555.                
  3556.                
  3557.                
  3558.             }else {
  3559.                 echo "<script>alert('ERROR , Selecione o tipo!');</script>";
  3560.             }
  3561.             
  3562.         }
  3563.         return $this->render('index/recebimento.html.twig', [
  3564.     
  3565.             
  3566.             'p'=>$p,
  3567.             'erro'=>$erro,
  3568.             'pagina' => $pagina,
  3569.             'etapa'=>$etapa,
  3570.             'caixas_setor' => $caixas_setor,
  3571.             'cx_setor' => $cx_setor
  3572.             
  3573.             
  3574.         ]);
  3575.     }
  3576.     #[Route('/index/higienizacao/{id}'name'higienizacao')]
  3577.     public function higienizacaoPaginatorInterface $paginator,Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer,$id): Response
  3578.     {
  3579.         $user_logado $this->getUser();
  3580.         $user_nome $user_logado->getNome();
  3581.         $date_hoje = new \DateTimeImmutable('America/Sao_Paulo');
  3582.         $ip_cliente $_SERVER['REMOTE_ADDR'];
  3583.         $erro '';
  3584.         $pagina 'home';
  3585.         $p ='';
  3586.         $a ;
  3587.         $clienteAll null;
  3588.         $cx null;
  3589.         $caixa null
  3590.         $etapa $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  3591.         $fluxo $etapa->getFluxo();
  3592.         $etapa_caixas $etapa->getCaixa()->toArray();
  3593.         $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo->getId());
  3594.        
  3595.         $e 0;
  3596.         $f 0;
  3597.         $clienteId $session->get('cliente_id');
  3598.         if($clienteId == null){
  3599.             
  3600.             return $this->redirectToRoute('home');
  3601.         }
  3602.         
  3603.         
  3604.         foreach ($etapa_caixas as $key) {
  3605.             $e++;
  3606.         }
  3607.         foreach ($fluxo_caixas as $key) {
  3608.             $f++;
  3609.         }
  3610.         if(isset($_POST["a"])){
  3611.             $a 2;
  3612.         }
  3613.         
  3614.         $qrCodeData $request->request->get('qrcode');
  3615.         if(isset($_POST["id_caixas"])){
  3616.             $a ;
  3617.             $caixa $doctrine->getRepository(Caixa::class)->findBy(['id' => $_POST["id_caixas"]]);
  3618.             
  3619.             foreach ($caixa as $key) { $caixa_cx_id $key->getClientes()->toArray();}
  3620.             
  3621.             $cx =  $caixa_cx_id ;
  3622.             
  3623.             foreach ($cx as $key) {$cliente_cx_id $key->getClienteAll()->getId();}
  3624.             
  3625.             $clienteAll $doctrine->getRepository(ClienteAll::class)->findClienteWithRelations($cliente_cx_id);
  3626.            
  3627.             
  3628.         }
  3629.         if($qrCodeData != null){
  3630.             
  3631.             $url $qrCodeData;
  3632.             preg_match('/(\d+)\/(\d+)$/'$url$matches);
  3633.             if (!empty($matches)) {
  3634.                 $numero1 $matches[1]; 
  3635.                 $numero2 $matches[2];
  3636.                 $clienteAll $doctrine->getRepository(ClienteAll::class)->find($numero1);
  3637.                 $cx $doctrine->getRepository(Cx::class)->findBy(['nome' => $numero2]);
  3638.                 
  3639.                 foreach ($cx as $key) {
  3640.                     $cx_id $key->getId();
  3641.                 }
  3642.                     
  3643.                 
  3644.                 $caixa $doctrine->getRepository(Caixa::class)->findBy(['cx' => $cx_id ]);
  3645.                 $a ;
  3646.                 
  3647.             } else {
  3648.                 
  3649.               
  3650.             }
  3651.             
  3652.         }
  3653.         if(isset($_POST["cx"])){
  3654.             $clienteAll $doctrine->getRepository(ClienteAll::class)->findClienteWithRelations($_POST["clienteAll"]);
  3655.             $clienteAll_nome $clienteAll->getNome();
  3656.             
  3657.             $cx $doctrine->getRepository(Cx::class)->find($_POST["cx"]);
  3658.             $caixa $doctrine->getRepository(Caixa::class)->find($_POST["caixas"]);
  3659.             $cliente $doctrine->getRepository(Cliente::class)->find($_POST["cliente"]);
  3660.             
  3661.             if ($cx != null) {
  3662.                 $cx_nome 'ID: '.$cx->getNome();
  3663.             }else{
  3664.                 $cx_nome 'GED: '.$caixa->getNome();
  3665.             }
  3666.         
  3667.             $cliente_nome $clienteAll_nome;
  3668.             if ($cliente_nome == NULL){
  3669.                 $cliente_nome $cliente->getNome();
  3670.             }
  3671.             
  3672.             
  3673.             $registro = new Registro();
  3674.             $registro->setOperacao('HIGIENIZAÇÃO '.$cx_nome); 
  3675.             $registro->setUser($user_nome);
  3676.             $registro->setCliente($cliente_nome);
  3677.             $registro->setIp($ip_cliente);
  3678.             $entityManager->persist($registro);
  3679.             $entityManager->flush();
  3680.             
  3681.             if($cx != null){
  3682.                 
  3683.                 $etapa->addCx($cx);
  3684.             }
  3685.             
  3686.             $etapa->addCaixa($caixa);
  3687.             $caixa->setHigienizaAt($date_hoje);
  3688.             $e++;
  3689.             if ($e == $f) {
  3690.                 
  3691.                 $registro = new Registro();
  3692.                 $registro->setOperacao('HIGIENIZAÇÃO DE '.$f' CAIXA(S)'); 
  3693.                 $registro->setUser('CONCLUIDO PELA EQUIPE');
  3694.                 $registro->setCliente($cliente_nome);
  3695.                 $registro->setIp($ip_cliente);
  3696.                 $entityManager->persist($registro);
  3697.                 $entityManager->flush();
  3698.                 $etapa->setRegistro($registro);
  3699.                 $etapa->setUpdatedAt($date_hoje);
  3700.                 $entityManager->flush();
  3701.             }
  3702.             
  3703.             $entityManager->flush();
  3704.             $erro 'ok';
  3705.             $p "Etapa concluída com sucesso";
  3706.         }
  3707.         
  3708.         return $this->render('index/higienizacao.html.twig', [
  3709.     
  3710.             'id'=>$id,
  3711.             'p'=>$p,
  3712.             'erro'=>$erro,
  3713.             'pagina' => $pagina,
  3714.             'a'=>$a,
  3715.             'clienteAll' => $clienteAll,
  3716.             'cx' =>$cx ,
  3717.             'caixa' => $caixa,
  3718.             'fluxo_caixas'=>$fluxo_caixas
  3719.             
  3720.             
  3721.             
  3722.         ]);
  3723.     }
  3724.    
  3725.     #[Route('/index/digitalizacao/{id}'name'digitalizacao')]
  3726.     public function digitalizacao(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $session,MessageBusInterface $bus,$id): Response
  3727.     {
  3728.         $ip_cliente $_SERVER['REMOTE_ADDR'];
  3729.         $etapa $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  3730.         $fluxo $doctrine->getRepository(Fluxo::class)->findWithAllRelations($etapa->getFluxo()->getId());
  3731.         $cliente_nome $fluxo->getCliente()->getNome();
  3732.         $cliente_id $fluxo->getCliente();
  3733.         $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo->getId());
  3734.         $form $this->createForm(UploadType::class);
  3735.         $user_logado $this->getUser();
  3736.         $user_logado_id $user_logado->getId();
  3737.         $userId $user_logado_id;
  3738.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  3739.         $form->handleRequest($request);
  3740.         $dotenv = new Dotenv();
  3741.         $dotenv->load(__DIR__.'/.env');
  3742.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  3743.         $hoje_formt=$hoje->format('Y-m-d') ;
  3744.         $dia_prod 'de hoje';
  3745.         $erro '';
  3746.         $ii=0;
  3747.         $pagina 'export';
  3748.         $p '';
  3749.         $uuid Uuid::v4();
  3750.         $user $this->getUser();
  3751.         $user_nome$user->getEmail();
  3752.         $user_nome_name$user->getNome();
  3753.         $pasta_user=$user_nome.'/';
  3754.         $cliente_alls "";
  3755.         $arr = [];
  3756.         $arrr=0;
  3757.         $f 0;
  3758.         $dt '';
  3759.         $clientS3 = new  S3Client([
  3760.             'region'  => 'sa-east-1',
  3761.             'version' => 'latest',
  3762.             'credentials' => [ 
  3763.                 'key'    => $_ENV['AWS_KEY'],
  3764.                 'secret' => $_ENV['AWS_SECRET'],
  3765.             ],
  3766.         
  3767.         ]);
  3768.         foreach ($fluxo_caixas as $key) {
  3769.             $f++;
  3770.         }
  3771.         if(isset($_POST["btn_cliente"])){
  3772.             
  3773.             $session->set('cliente_id'$_POST["btn_cliente"]);
  3774.             return $this->redirectToRoute('home');
  3775.         }
  3776.        
  3777.             
  3778.             
  3779.        
  3780.         $clienteId $session->get('cliente_id');
  3781.         
  3782.         if ($clienteId == null ) {
  3783.             
  3784.             $caixas =  "";
  3785.             $cliente_session "";
  3786.             return $this->redirectToRoute('home');
  3787.        
  3788.         } else {
  3789.             
  3790.             $caixas $fluxo_caixas;
  3791.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);       
  3792.         }
  3793.         
  3794.         
  3795.         if(isset($_POST["botao_export"]))
  3796.         {
  3797.             
  3798.             $caixaId $_POST["caixas"];
  3799.             
  3800.             $caixa_id $doctrine->getRepository(Caixa::class)->find($_POST["caixas"]);
  3801.             $clientes$cliente_id->getId();
  3802.             $clienteId=$clientes;
  3803.             $clientes_status$cliente_id->getExtraFields();
  3804.             if(!$clientes_status){
  3805.                 $clientes_status="ged";
  3806.             }
  3807.             $conteiner $_POST["conteiner"];
  3808.             $cont_file ;
  3809.             $umlautString =$cliente_nome;
  3810.             $slugger = new AsciiSlugger();
  3811.             $teste=$slugger->slug($umlautString$seperator '-')->toString();
  3812.             $caminho strtolower ($teste.'/');
  3813.                     
  3814.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  3815.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  3816.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  3817.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  3818.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  3819.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  3820.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  3821.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  3822.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  3823.             if($clientes ==  40){$caminho='fasf-atas-e-diario/';}
  3824.             if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  3825.            
  3826.             $filesTmp  $_FILES['file']['tmp_name'];
  3827.             $filesName $_FILES['file']['name'];
  3828.             
  3829.             foreach ($filesTmp as $index => $file) {
  3830.             
  3831.                 $uuid Uuid::v4();
  3832.                 $cont_file++;
  3833.                 // nome original do arquivo
  3834.                 $originalName pathinfo($filesName[$index], PATHINFO_FILENAME);
  3835.                 // sanitiza o nome (remove acentos, espaços estranhos etc.)
  3836.                 $slugger = new AsciiSlugger();
  3837.                 $safeName strtolower($slugger->slug($originalName)->toString());
  3838.             
  3839.                 // 🔹 Se cliente for local, usa nome original
  3840.                 if ($clientes_status === 'local') {
  3841.             
  3842.             
  3843.                     $filename $safeName '.pdf';
  3844.             
  3845.                 } else {
  3846.                     // padrão: UUID
  3847.                     $filename $uuid '.pdf';
  3848.                 }
  3849.             
  3850.                 $tempDir __DIR__ '/../../var/uploads/messenger';
  3851.                 if (!is_dir($tempDir)) {
  3852.                     mkdir($tempDir0777true);
  3853.                 }
  3854.             
  3855.                 $tempFilePath $tempDir '/' $filename;
  3856.             
  3857.                 move_uploaded_file($file$tempFilePath);
  3858.                 chmod($tempFilePath0644);
  3859.                 if (!file_exists($tempFilePath) || filesize($tempFilePath) === 0) {
  3860.                     throw new \RuntimeException(
  3861.                         'Falha ao gravar PDF temporário: ' $tempFilePath
  3862.                     );
  3863.                 }
  3864.                 
  3865.                 // evita race condition de filesystem
  3866.                 clearstatcache(true$tempFilePath);
  3867.             
  3868.                 $bus->dispatch(new UploadMultipartMessage(
  3869.                     $tempFilePath,
  3870.                     $filename,
  3871.                     $caminho,
  3872.                     '',
  3873.                     $caixaId,
  3874.                     $clienteId,
  3875.                     $userId,
  3876.                     0,
  3877.                     $conteiner,
  3878.                     $clientes,
  3879.                     $clientes_status,
  3880.                     $safeName,
  3881.                     $originalName,
  3882.                     $cliente_alls 
  3883.                 ));
  3884.             }
  3885.            
  3886.             $log = new Registro();
  3887.             $log->setOperacao('EXPORTOU '.$cont_file.' DOCUMENTO(S)'); 
  3888.             $log->setUser($user_nome_name);
  3889.             $log->setCliente($cliente_nome);
  3890.             $entityManager->persist($log);
  3891.             $entityManager->flush();
  3892.             
  3893.             return $this->redirectToRoute('digitalizacao', ['id' => $id]);
  3894.             
  3895.         
  3896.         }
  3897.         if(isset($_POST["caixa_total"])){
  3898.             $caixa_total $_POST["caixa_total"];
  3899.             $documento_total =$_POST["documento_total"];
  3900.             $qtd_total =$_POST["qtd_total"];
  3901.                 $registro = new Registro();
  3902.                 $registro->setOperacao('DIGITALIZAÇÃO:  '.$caixa_total' CAIXA(S) / '.$documento_total.' DOCUMENTO(S) / '.$qtd_total.' IMAGEN(S)'); 
  3903.                 $registro->setUser('CONCLUIDO PELA EQUIPE');
  3904.                 $registro->setCliente($cliente_nome);
  3905.                 $registro->setIp($ip_cliente);
  3906.                 $entityManager->persist($registro);
  3907.                 $entityManager->flush();
  3908.                 $etapa->setRegistro($registro);
  3909.                 $etapa->setUpdatedAt($hoje);
  3910.                 $entityManager->flush();
  3911.                 $erro 'ok';
  3912.                 $p "Etapa concluída com sucesso";
  3913.         }
  3914.        
  3915.         return $this->render('index/digitalizacao.html.twig', [
  3916.             'id'=>$id,
  3917.             'p'=>$p,
  3918.             'erro'=>$erro,
  3919.             'pagina' => $pagina,
  3920.             'caixas' => $caixas,
  3921.             'user_logado' => $user_logado,
  3922.             'cliente' => $cliente,
  3923.             'cliente_session' => $cliente_session,
  3924.             'form' => $form->createView(),
  3925.             'dia_prod' => $dia_prod,
  3926.             'fluxo' => $fluxo
  3927.         ]);
  3928.     }
  3929.     #[Route('/index/indexacao/{id}'name'indexacao')]
  3930.     public function indexacao(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManager SessionInterface $session,$id): Response
  3931.     {   
  3932.         $ip_cliente $_SERVER['REMOTE_ADDR'];
  3933.         $etapa $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  3934.         $fluxo $doctrine->getRepository(Fluxo::class)->findWithAllRelations($etapa->getFluxo()->getId());
  3935.         $cliente_nome $fluxo->getCliente()->getNome();
  3936.         $cliente_etapa $fluxo->getCliente();
  3937.         $fluxo_caixas $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo->getId());
  3938.         $caixaIds array_map(fn($caixa) => $caixa->getId(), $fluxo_caixas);
  3939.         $documentoRepository $entityManager->getRepository(Documento::class);
  3940.         $query $documentoRepository->createQueryBuilder('d')
  3941.             ->where('d.caixa IN (:caixaIds)')
  3942.             ->setParameter('caixaIds'$caixaIds)
  3943.             #->orderBy('d.qtd', 'ASC') // Ordenando pelo ID da caixa em ordem crescente
  3944.             ->getQuery();
  3945.         // Executa a query
  3946.         $documentos $query->getResult();
  3947.         $caixas $fluxo_caixas;
  3948.         $dotenv = new Dotenv();
  3949.         $dotenv->load(__DIR__.'/.env');
  3950.         $user_logado $this->getUser();
  3951.         $form $this->createForm(UploadType::class);
  3952.         $form->handleRequest($request);
  3953.         $user_logado_tipoAcesso $user_logado->getTipoAcesso();
  3954.         $user_logado_nome $user_logado->getNome();
  3955.         $user_logado_id $user_logado->getId();
  3956.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  3957.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  3958.         $hoje_formt=$hoje->format('Y-m-d');
  3959.         $doc $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome$hoje_formt);
  3960.         $dia_prod 'de hoje';
  3961.         $permissao = [];
  3962.         $list_indexador = [];
  3963.         $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $cliente_etapa]);
  3964.         $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $cliente_etapa]);
  3965.         $cliente_ids =$cliente_etapa ;
  3966.         
  3967.        
  3968.             
  3969.         $cliente_nome$cliente_ids->getNome();
  3970.         $clientes$cliente_ids->getId();
  3971.         $umlautString =$cliente_nome;
  3972.         $slugger = new AsciiSlugger();
  3973.         $teste=$slugger->slug($umlautString$seperator '-')->toString();
  3974.         $caminho strtolower ($teste.'/');
  3975.                         
  3976.         if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  3977.         if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  3978.         if($clientes == 35){$caminho='pmecj-sp-saude/';}
  3979.         if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  3980.         if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  3981.         if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  3982.         if($clientes ==  15){$caminho='cbsi-dossies/';}
  3983.         if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  3984.         if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  3985.         if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  3986.       
  3987.           
  3988.         if(isset($_POST["btn_cliente"])){
  3989.             
  3990.             $session->set('cliente_id'$_POST["btn_cliente"]);
  3991.             return $this->redirectToRoute('home');
  3992.         }
  3993.         $clienteId $session->get('cliente_id');
  3994.         
  3995.         
  3996.         if ($clienteId == null ) {
  3997.             
  3998.             $caixas =  "";
  3999.             $cliente_session "";
  4000.             return $this->redirectToRoute('home');
  4001.        
  4002.         }
  4003.            
  4004.         $erro '';
  4005.         $ii=0;
  4006.         $pagina 'index';
  4007.         $p '';
  4008.         $link '';
  4009.         $mx 0;
  4010.         $xy 
  4011.         $yz 
  4012.         $ay ;
  4013.         $ky ;
  4014.         $pdf ='';
  4015.         $pagina_h4 ='Documento(s) para indexar';
  4016.         $nome_menu_ '';
  4017.         $index_tipo='';
  4018.         $uuid Uuid::v4();
  4019.         $user $this->getUser();
  4020.         $user_nome$user->getEmail();
  4021.         $user_nome_name$user->getNome();
  4022.         $pasta_user=$user_nome.'/';
  4023.         $arr = [];
  4024.         $arrr=0;
  4025.         $index_find null;
  4026.         $dt '';
  4027.         $clientS3 = new  S3Client([
  4028.                     'region'  => 'sa-east-1',
  4029.                     'version' => 'latest',
  4030.                     'credentials' => [ 
  4031.                         'key'    => $_ENV['AWS_KEY'],
  4032.                         'secret' => $_ENV['AWS_SECRET'],
  4033.                     ],
  4034.                 ]);
  4035.         
  4036.      
  4037.             
  4038.        
  4039.         if(isset($_POST["botao_index"])){
  4040.             
  4041.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4042.             $link $pdf->getImage();
  4043.             $xy ;
  4044.             
  4045.         }
  4046.         if(isset($_POST["botao_doc"])){
  4047.             
  4048.             
  4049.             $yz ;
  4050.             $xy ;
  4051.             $ay ;
  4052.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4053.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4054.            
  4055.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4056.             $index_tipo_tipo =  $index_tipo->getNome();
  4057.             $link $pdf->getImage();
  4058.             $fase=$_POST["fase"];
  4059.             $data $_POST["data"];
  4060.             $cx $_POST["caixas"];
  4061.             $classifica $_POST["classifica"];
  4062.             $desc $_POST["desc"];
  4063.             $assunto $_POST["assunto"];
  4064.             $chave $_POST["chave"];
  4065.             $nome $_POST["nome"];
  4066.             $conteiner $_POST["conteiner"];
  4067.             
  4068.             
  4069.             $caixa_id $doctrine->getRepository(Caixa::class)->find($cx);
  4070.             
  4071.             
  4072.             
  4073.             
  4074.             // Exibe os números encontrados
  4075.             
  4076.             if ($clientes != 7) {
  4077.                 preg_match_all('/\d+/'$fase$matches);
  4078.                 $numeros array_map('intval'$matches[0]);
  4079.                 if ($data != "") {
  4080.                     if ($numeros != [] ) {
  4081.                         if ($fase != "") {
  4082.         
  4083.                             // Número inteiro que você deseja somar ao ano
  4084.                             $numeroParaSomar $numeros[0];
  4085.         
  4086.                             // Extrair o ano da data
  4087.                             list($ano$mes$dia) = explode('-'$data);
  4088.         
  4089.                             // Converter o ano para um número inteiro
  4090.                             $ano intval($ano);
  4091.         
  4092.                             // Somar o número ao ano
  4093.                             $data_vecimento =  $ano $numeroParaSomar.'-'.$mes.'-'$dia;
  4094.         
  4095.                             $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  4096.         
  4097.                         }
  4098.                 }
  4099.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  4100.                 }
  4101.             }    
  4102.             
  4103.             if ($clientes == 7) {
  4104.                   $pdf->setVencimentoDocumento(new \DateTimeImmutable($fase));
  4105.                   $pdf->setDataDocumento(new \DateTimeImmutable($data));
  4106.              }
  4107.             
  4108.             
  4109.             $pdf->setAssunto($assunto);
  4110.             if ($classifica != "") {
  4111.                 $classifica_id $doctrine->getRepository(Classificacao::class)->find($classifica);
  4112.                 $pdf->setClassificacao($classifica_id);
  4113.             }
  4114.             $pdf->setCaixa($caixa_id);
  4115.             $pdf->setExtraFields($desc);
  4116.             $pdf->setNome($nome);
  4117.             $pdf->setKeywords($chave);
  4118.             $pdf->setUserIndex($user_nome_name);
  4119.             $pdf->setConteiner($conteiner);
  4120.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  4121.             $pdf->setTipo($index_tipo);
  4122.             $entityManager->flush();
  4123.             $id_pd $pdf->getId();    
  4124.             $log = new Registro();
  4125.             $log->setOperacao('Indexou o Documento com id '.$id_pd); 
  4126.             $log->setUser($user_nome_name);
  4127.             $log->setCliente($cliente_nome);
  4128.             $entityManager->persist($log);
  4129.             $entityManager->flush();
  4130.             $erro 'ok';
  4131.             $p =  $index_tipo_tipo.' indexado com sucesso';
  4132.             
  4133.            
  4134.             
  4135.            
  4136.         }   
  4137.         if(isset($_POST["botao_index_edit"])){
  4138.             
  4139.             $yz ;
  4140.             $xy ;
  4141.             $ay ;
  4142.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4143.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4144.             $link $pdf->getImage();
  4145.         }
  4146.         if(isset($_POST["botao_volta"])){
  4147.             $xy ;
  4148.             $yz ;
  4149.         }
  4150.         if(isset($_POST["index_button"])){
  4151.             
  4152.             
  4153.             $yz ;
  4154.             $xy ;
  4155.             $ay ;
  4156.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4157.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["index_button"]);
  4158.             $link $pdf->getImage();
  4159.         }
  4160.         if(isset($_POST["botao_cancel"])){
  4161.             $yz ;
  4162.             $xy ;
  4163.             $ay ;
  4164.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4165.             $link $pdf->getImage();
  4166.             
  4167.         }
  4168.         if(isset($_POST["delet"])){
  4169.            
  4170.             $ky ;
  4171.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["delet"]);
  4172.             $documentos $doctrine->getRepository(Documento::class)->findBy(['id' => $_POST["delet"]]);
  4173.             
  4174.             if($pdf->getTipo()!= null){
  4175.                 $index_find =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  4176.                 $pagina =$index_find->getTipo();
  4177.                 $pagina_h4 ='Documento(s) do tipo ( '.$index_find->getTipo().' )';
  4178.             }
  4179.                         
  4180.         }
  4181.         if(isset($_POST["delet_cancel"])){
  4182.             $ky ;
  4183.         }
  4184.         if(isset($_POST["delet_sim"])){
  4185.             
  4186.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4187.             $id_pd $pdf->getId();
  4188.             $entityManager->remove($pdf);
  4189.             $entityManager->flush();
  4190.           
  4191.             $log = new Registro();
  4192.             $log->setOperacao('Excluiu Documento com id '.$id_pd); 
  4193.             $log->setUser($user_nome_name);
  4194.             $log->setCliente($cliente_nome);
  4195.             $entityManager->persist($log);
  4196.             $entityManager->flush();
  4197.             $erro 'ok';
  4198.             $p 'Documento com id '.$id_pd.' excluido com sucesso '
  4199.         }
  4200.         if(isset($_POST["index_edit"])){
  4201.             $yz ;
  4202.             $xy ;
  4203.             $ay ;
  4204.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4205.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4206.             $link $pdf->getImage();
  4207.         }
  4208.        
  4209.         if(isset($_POST["caixa_total"])){
  4210.             $caixa_total $_POST["caixa_total"];
  4211.             $documento_total =$_POST["documento_total"];
  4212.             $qtd_total =$_POST["qtd_total"];
  4213.                 $registro = new Registro();
  4214.                 $registro->setOperacao('INDEXADO:  '.$caixa_total' CAIXA(S) / '.$documento_total.' DOCUMENTO(S) / '); 
  4215.                 $registro->setUser('CONCLUIDO PELA EQUIPE');
  4216.                 $registro->setCliente($cliente_nome);
  4217.                 $registro->setIp($ip_cliente);
  4218.                 $entityManager->persist($registro);
  4219.                 $entityManager->flush();
  4220.                 $etapa->setRegistro($registro);
  4221.                 $etapa->setUpdatedAt($hoje);
  4222.                 $entityManager->flush();
  4223.                 $erro 'ok';
  4224.                 $p "Etapa concluída com sucesso";
  4225.         }
  4226.         
  4227.            $cmd $clientS3->getCommand('GetObject', [
  4228.                 'Bucket' => 'arquivosdoc',
  4229.                 'Key'    => $caminho$link
  4230.             ]);
  4231.             
  4232.             $req $clientS3->createPresignedRequest($cmd'+30 minutes');
  4233.             $all_Url = (string) $req->getUri();
  4234.         
  4235.         return $this->render('index/indexacao.html.twig', [
  4236.             'documentos' => $documentos,
  4237.             'xy' => $xy,
  4238.             'yz' => $yz,
  4239.             'ay'=>$ay,
  4240.             'link' => $link,
  4241.             'pdf'=>$pdf,
  4242.             'p'=>$p,
  4243.             'erro'=>$erro,
  4244.             'index_all'=>$index_all,
  4245.             'index_tipo'=>$index_tipo,
  4246.             'ky'=>$ky,
  4247.             'pagina' => $pagina,
  4248.             'pagina_h4' =>$pagina_h4,
  4249.             'index_find'=>$index_find,
  4250.             'mx'=>$mx,
  4251.             'class'=>$class,
  4252.             'caixas' => $caixas,
  4253.             'permissao'=>$permissao,
  4254.             'doc'=>$doc,
  4255.             'dia_prod' => $dia_prod,
  4256.             'fluxo' => $fluxo,
  4257.             'id' => $id,
  4258.             'caminho' =>$caminho,
  4259.             'clientes'=>$clientes,
  4260.             'all_Url'=>$all_Url
  4261.         ]);
  4262.     }
  4263.     
  4264.     #[Route('/kpis'name'kpis')]
  4265.     public function kpis(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManager): Response
  4266.     {
  4267.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  4268.         $hoje_formt=$hoje->format('Y-m-d') ;
  4269.         $pagina="kpis";
  4270.         $motivo ='';
  4271.         $error='';
  4272.         $user_logado $this->getUser();
  4273.         $de_="";
  4274.         $ate_"";
  4275.         $h4 ="TOTAL";
  4276.         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  4277.             $ip_cliente explode(','$_SERVER['HTTP_X_FORWARDED_FOR'])[0];
  4278.         } else {
  4279.             $ip_cliente $_SERVER['REMOTE_ADDR'];
  4280.         }
  4281.         
  4282.         $payload json_encode([
  4283.             
  4284.             'data_inicio' => null,
  4285.             'data_fim' => null
  4286.             
  4287.         ]);
  4288.         $options = [
  4289.             'http' => [
  4290.                 'header'  => "Content-Type: application/json\r\n",
  4291.                 'method'  => 'POST',
  4292.                 'content' => $payload,
  4293.             ],
  4294.         ];
  4295.         $context  stream_context_create($options);
  4296.         $response file_get_contents('https://produtive.arquivosdoc.com.br/api/tjrj'false$context);
  4297.         if ($response === false) {
  4298.             return new Response("Erro ao consumir API"500);
  4299.         }
  4300.         $data json_decode($responsetrue);
  4301.         
  4302.         $conn $entityManager->getConnection();
  4303.         $sql "
  4304.            SELECT 
  4305.                 c.nome AS cliente_nome,
  4306.                     (SELECT COUNT(cx.id) 
  4307.                      FROM cx cx 
  4308.                      WHERE cx.caminho IS NOT NULL 
  4309.                      AND cx.cliente_id = c.id) AS total_caixas,
  4310.                     (SELECT COUNT(d.id) 
  4311.                      FROM documento d 
  4312.                      JOIN cliente s ON s.id = d.cliente_id
  4313.                      WHERE s.cliente_all_id = c.id) AS total_documentos,
  4314.                     (SELECT SUM(d.qtd) 
  4315.                      FROM documento d 
  4316.                      JOIN cliente s ON s.id = d.cliente_id
  4317.                      WHERE s.cliente_all_id = c.id) AS imagens_total
  4318.                 FROM cliente_all c
  4319.                 ORDER BY c.nome ASC
  4320.         ";
  4321.         $stmt $conn->prepare($sql);
  4322.         $stmt->execute();
  4323.         $fed_cliente $stmt->executeQuery()->fetchAllAssociative();
  4324.         
  4325.          // 🔹 Adicionando TJRJ no array de clientes
  4326.         if (is_array($data)) {
  4327.             $fed_cliente[] = [
  4328.                 'cliente_nome'     => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  4329.                  #'total_caixas'     => $data['total_caixas'] ?? 0,
  4330.                 'total_caixas'     => 0,
  4331.                 'total_documentos' => $data['total_documentos'] ?? 0,
  4332.                 'imagens_total'    => $data['imagens_total'] ?? 0
  4333.             ];
  4334.         }
  4335.         
  4336.        
  4337.        
  4338.         //IMAGENS
  4339.         $sql1 "SELECT SUM(d.qtd) AS total_imagens FROM documento d";
  4340.         $totalImagens $conn->fetchOne($sql1); 
  4341.         $totalImagens += $data['imagens_total'] ?? 0;
  4342.         
  4343.         //DOCUMENTOS
  4344.         $sql2 "SELECT COUNT(d.id) AS total_documentos FROM documento d";
  4345.         $documento $conn->fetchOne($sql2);
  4346.         $documento += $data['total_documentos'] ?? 0;
  4347.         
  4348.         //CX (com filtro de status != 0)
  4349.         $sql3 "SELECT COUNT(d.id) AS total_cx FROM cx d WHERE d.status != 0 AND d.caminho != ''";
  4350.         $cx $conn->fetchOne($sql3);
  4351.         
  4352.         
  4353.          if(isset($_POST["pesq"])){
  4354.         
  4355.             
  4356.             $de $_POST["de"];
  4357.             $ate $_POST["ate"]." 23:59:59";
  4358.             
  4359.             
  4360.             
  4361.             // IMAGENS
  4362.             $queryStr '
  4363.                 SELECT SUM(d.qtd) AS total_imagens
  4364.                 FROM App\Entity\Documento d
  4365.                 WHERE d.createdAt >= :de 
  4366.             ';
  4367.             if ($ate) {
  4368.                 $queryStr .= ' AND d.createdAt <= :ate';
  4369.             }
  4370.             $query $entityManager->createQuery($queryStr);
  4371.             $query->setParameter('de'$de);
  4372.             if ($ate) {$query->setParameter('ate'$ate);}
  4373.             $result $query->getSingleResult();
  4374.             $totalImagens $result['total_imagens'];
  4375.             //
  4376.         
  4377.             // DOCUMENTOS
  4378.             $queryStr '
  4379.                 SELECT COUNT(d.id) AS total_documentos
  4380.                 FROM App\Entity\Documento d
  4381.                 WHERE d.createdAt >= :de
  4382.             ';
  4383.             if ($ate) {
  4384.                 $queryStr .= ' AND d.createdAt <= :ate';
  4385.             }
  4386.             $query $entityManager->createQuery($queryStr);
  4387.             $query->setParameter('de'$de);
  4388.             if ($ate) {$query->setParameter('ate'$ate);}
  4389.             $result $query->getSingleResult();
  4390.             $documento $result['total_documentos'];
  4391.             //
  4392.         
  4393.             // CX
  4394.             $queryStr '
  4395.                 SELECT COUNT(d.id) AS total_cx
  4396.                 FROM App\Entity\Cx d
  4397.                 WHERE d.createdAt >= :de  AND d.caminho IS NOT NULL
  4398.             ';
  4399.             if ($ate) {
  4400.                 $queryStr .= ' AND d.createdAt <= :ate';
  4401.             } else {
  4402.                 $queryStr .= ' AND DATE(d.createdAt) = DATE(:de)';
  4403.             }
  4404.             $query $entityManager->createQuery($queryStr);
  4405.             $query->setParameter('de'$de);
  4406.             if ($ate) {$query->setParameter('ate'$ate);}
  4407.             $result $query->getSingleResult();
  4408.             $cx $result['total_cx'];
  4409.             //
  4410.             
  4411.             $queryStr "
  4412.                 SELECT 
  4413.                     c.nome AS cliente_nome,
  4414.                     (SELECT COUNT(cx.id) 
  4415.                      FROM App\Entity\Cx cx 
  4416.                      WHERE cx.status != 0 
  4417.                      AND cx.caminho != '' 
  4418.                      AND cx.cliente = c
  4419.                      AND cx.createdAt >= :de
  4420.             ";
  4421.             
  4422.             if ($ate) {
  4423.                 $queryStr .= " AND cx.createdAt <= :ate";
  4424.             } else {
  4425.                 $queryStr .= " AND DATE(cx.createdAt) = DATE(:de)";
  4426.             }
  4427.             
  4428.             $queryStr .= ") AS total_caixas,
  4429.         
  4430.                     (SELECT COUNT(d1.id) 
  4431.                      FROM App\Entity\Documento d1 
  4432.                      JOIN d1.cliente c1 
  4433.                      WHERE c1.clienteAll = c
  4434.                      AND d1.createdAt >= :de
  4435.             ";
  4436.             
  4437.             if ($ate) {
  4438.                 $queryStr .= " AND d1.createdAt <= :ate";
  4439.             } else {
  4440.                 $queryStr .= " AND DATE(d1.createdAt) = DATE(:de)";
  4441.             }
  4442.             
  4443.             $queryStr .= ") AS total_documentos,
  4444.         
  4445.                     (SELECT SUM(d2.qtd) 
  4446.                      FROM App\Entity\Documento d2 
  4447.                      JOIN d2.cliente c2 
  4448.                      WHERE c2.clienteAll = c
  4449.                      AND d2.createdAt >= :de
  4450.             ";
  4451.             
  4452.             if ($ate) {
  4453.                 $queryStr .= " AND d2.createdAt <= :ate";
  4454.             } else {
  4455.                 $queryStr .= " AND DATE(d2.createdAt) = DATE(:de)";
  4456.             }
  4457.             
  4458.             $queryStr .= ") AS imagens_total
  4459.             FROM App\Entity\ClienteAll c
  4460.             ORDER BY c.nome ASC
  4461.             ";
  4462.             
  4463.             // Preparar a consulta com os parâmetros de data
  4464.             $query $entityManager->createQuery($queryStr);
  4465.             $query->setParameter('de'$de);
  4466.             if ($ate) {
  4467.                 $query->setParameter('ate'$ate);
  4468.             }
  4469.             
  4470.             $result $query->getResult();
  4471.                     
  4472.             $fed_cliente $result;
  4473.             
  4474.             
  4475.             
  4476.             // 🔹 Chamada API TJRJ
  4477.             $payload json_encode([
  4478.                 'data_inicio' => $_POST["de"] ?? null,
  4479.                 'data_fim'    => $_POST["ate"] ?? null
  4480.             ]);
  4481.             
  4482.             $options = [
  4483.                 'http' => [
  4484.                     'header'  => "Content-Type: application/json\r\n",
  4485.                     'method'  => 'POST',
  4486.                     'content' => $payload,
  4487.                 ],
  4488.             ];
  4489.             
  4490.             $context  stream_context_create($options);
  4491.             $response file_get_contents('https://produtive.arquivosdoc.com.br/api/tjrj'false$context);
  4492.             
  4493.             $data $response json_decode($responsetrue) : [];
  4494.             
  4495.             // 🔹 Adiciona TJRJ na lista final (igual no geral)
  4496.             if (is_array($data)) {
  4497.                 $fed_cliente[] = [
  4498.                     'cliente_nome'     => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  4499.                     'total_caixas'     => 0,
  4500.                     'total_documentos' => $data['total_documentos'] ?? 0,
  4501.                     'imagens_total'    => $data['imagens_total'] ?? 0
  4502.                 ];
  4503.             }
  4504.             
  4505.             
  4506.                     
  4507.                         
  4508.         } 
  4509.           
  4510.             
  4511.      
  4512.         
  4513.         return $this->render('index/kpis.html.twig',array(
  4514.             
  4515.             'error' =>$error,
  4516.             'motivo' => $motivo,
  4517.             'pagina'=>$pagina,
  4518.             'user_logado'=> $user_logado ,
  4519.             'cx' => $cx,
  4520.             'documento' => $documento,
  4521.             'de' =>$de_,
  4522.             'ate' =>$ate_,
  4523.             'h4' => $h4,
  4524.             //'documentosPorMes' => $documentosPorMes,
  4525.             //'cxPorMes'=>$cxPorMes,
  4526.             //'totalImagensPorMes' => $totalImagensPorMes,
  4527.             'totalImagens'=>$totalImagens,
  4528.             'fed_cliente'=> $fed_cliente
  4529.             
  4530.             
  4531.         ));
  4532.     }
  4533.     
  4534.     #[Route('/fila/count'name'fila_count'methods: ['GET'])]
  4535.     public function count(EntityManagerInterface $entityManager): JsonResponse
  4536.     {
  4537.         $user_logado $this->getUser();
  4538.         $user_logado_id $user_logado->getId();
  4539.         $count $entityManager->getRepository(MessengerMessages::class)->countPendingMessagesByUser($user_logado_id);
  4540.         
  4541.         return new JsonResponse(['count' => $count]);
  4542.     }
  4543.     
  4544.     #[Route('/index/qualidade'name'qualidade')]
  4545.     public function qualidade(Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManager SessionInterface $session): Response
  4546.     {   
  4547.         $clienteId $session->get('cliente_id');
  4548.         $ip_cliente $_SERVER['REMOTE_ADDR'];
  4549.         $caixaIds "LEONARDO DE SOUZA CRUZEIRO";
  4550.         $documentoRepository $entityManager->getRepository(Documento::class);
  4551.         $query $documentoRepository->createQueryBuilder('d')
  4552.             ->where('d.user_index IN (:caixaIds)')
  4553.             ->andWhere('d.cliente = :clienteId')
  4554.             ->andWhere('d.situacao = :situacao OR d.situacao IS NULL')
  4555.             ->setParameter('situacao''')
  4556.             ->setParameter('caixaIds'$caixaIds)
  4557.             ->setParameter('clienteId'$clienteId)
  4558.             ->orderBy('d.caixa''ASC'// Ordenando pelo ID da caixa em ordem crescente
  4559.             ->getQuery();
  4560.         // Executa a query
  4561.         $documentos $query->getResult();
  4562.         #dd($documentos);
  4563.         $dotenv = new Dotenv();
  4564.         $dotenv->load(__DIR__.'/.env');
  4565.         $user_logado $this->getUser();
  4566.         $form $this->createForm(UploadType::class);
  4567.         $form->handleRequest($request);
  4568.         $user_logado_tipoAcesso $user_logado->getTipoAcesso();
  4569.         $user_nome_name $user_logado->getNome();
  4570.         $user_logado_id $user_logado->getId();
  4571.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  4572.         $hoje_formt=$hoje->format('Y-m-d');
  4573.         $dia_prod 'de hoje';
  4574.         $permissao = [];
  4575.         $list_indexador = [];
  4576.         $slugger = new AsciiSlugger();
  4577.         $erro '';
  4578.         $ii=0;
  4579.         $pagina 'qualidade';
  4580.         $p '';
  4581.         $link '';
  4582.         $xy 
  4583.         $pdf ='';
  4584.         $umlautString '';
  4585.         $clientes 0;
  4586.         $caminho ='';
  4587.         $class ="";
  4588.         $all_Url="";
  4589.         
  4590.         $clientS3 = new  S3Client([
  4591.                     'region'  => 'sa-east-1',
  4592.                     'version' => 'latest',
  4593.                     'credentials' => [ 
  4594.                         'key'    => $_ENV['AWS_KEY'],
  4595.                         'secret' => $_ENV['AWS_SECRET'],
  4596.                     ],
  4597.                 ]);
  4598.        
  4599.         if(isset($_POST["botao_index"])){
  4600.             
  4601.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4602.             $clientes $pdf->getCliente()->getId();
  4603.             $clienteRepository $entityManager->getRepository(Cliente::class);
  4604.             $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $clientes]);
  4605.             $query $clienteRepository->createQueryBuilder('c')
  4606.                 ->where('c.id = :caixaIds')
  4607.                 ->setParameter('caixaIds'$clientes)
  4608.                 ->getQuery();
  4609.             $cl $query->getSingleResult();
  4610.             $link $pdf->getImage();
  4611.             $xy ;
  4612.             $umlautString $cl->getNome();
  4613.             $teste=$slugger->slug($umlautString$seperator '-')->toString();
  4614.             $caminho strtolower ($teste.'/');
  4615.                     
  4616.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  4617.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  4618.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  4619.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  4620.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  4621.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  4622.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  4623.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  4624.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  4625.             if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  4626.             
  4627.             $cmd $clientS3->getCommand('GetObject', [
  4628.                 'Bucket' => 'arquivosdoc',
  4629.                 'Key'    => $caminho$link
  4630.                 ]);
  4631.                 
  4632.             $req $clientS3->createPresignedRequest($cmd'+30 minutes');
  4633.             $all_Url = (string) $req->getUri();
  4634.                 
  4635.         }
  4636.         if(isset($_POST["botao_doc"])){
  4637.             
  4638.             
  4639.             
  4640.             
  4641.             $yz ;
  4642.             $xy ;
  4643.             $ay ;
  4644.             
  4645.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4646.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  4647.             $index_tipo_tipo =  $index_tipo->getNome();
  4648.             $link $pdf->getImage();
  4649.             $data $_POST["data"];
  4650.             $desc $_POST["desc"];
  4651.             $assunto $_POST["assunto"];
  4652.             $chave $_POST["chave"];
  4653.             $nome $_POST["nome"];
  4654.             $conteiner $_POST["conteiner"];
  4655.             $classifica $_POST["classifica"];
  4656.             $fase $_POST["fase"];
  4657.             
  4658.             preg_match_all('/\d+/'$fase$matches);
  4659.             $numeros array_map('intval'$matches[0]);
  4660.             if ($clientes != 7) {
  4661.                 if ($data != "") {
  4662.                     if ($fase != "") {
  4663.                         $numeroParaSomar $numeros[0];
  4664.                         list($ano$mes$dia) = explode('-'$data);
  4665.                         $ano intval($ano);
  4666.                         $data_vecimento =  $ano $numeroParaSomar.'-'.$mes.'-'$dia;
  4667.                         $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  4668.                     }
  4669.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  4670.                 }
  4671.             }  
  4672.             if ($classifica != "") {
  4673.                 $classifica_id $doctrine->getRepository(Classificacao::class)->find($classifica);
  4674.                 $pdf->setClassificacao($classifica_id);
  4675.             }
  4676.             
  4677.             
  4678.             
  4679.             
  4680.             $pdf->setAssunto($assunto);
  4681.             $pdf->setExtraFields($desc);
  4682.             $pdf->setNome($nome);
  4683.             $pdf->setKeywords($chave);
  4684.             $pdf->setUserIndex($user_nome_name);
  4685.             $pdf->setConteiner($conteiner);
  4686.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  4687.             $pdf->setSituacao('OK');
  4688.             $entityManager->flush();
  4689.             $id_pd $pdf->getId();    
  4690.             $log = new Registro();
  4691.             $log->setOperacao('Conferiu o Documento com id '.$id_pd); 
  4692.             $log->setUser($user_nome_name);
  4693.             $log->setCliente($umlautString);
  4694.             $entityManager->persist($log);
  4695.             $entityManager->flush();
  4696.             $erro 'ok';
  4697.             $p =  $index_tipo_tipo.' FOI CONFERIDO COM SUCESSO';
  4698.            
  4699.         }   
  4700.         if(isset($_POST["botao_volta"])){
  4701.             $xy ;
  4702.             $yz ;
  4703.         }
  4704.         
  4705.        
  4706.         
  4707.         return $this->render('index/qualidade.html.twig', [
  4708.             'documentos' => $documentos,
  4709.             'xy' => $xy,
  4710.             'link' => $link,
  4711.             'pdf'=>$pdf,
  4712.             'p'=>$p,
  4713.             'erro'=>$erro,
  4714.             'pagina' => $pagina,
  4715.             'caminho' =>$caminho,
  4716.             'class' => $class,
  4717.             'all_Url'=>$all_Url,
  4718.            
  4719.         ]);
  4720.     }
  4721.     
  4722.      #[Route('/metas'name'metas')]
  4723.     public function metasPaginatorInterface $paginator,Request $request,ManagerRegistry $doctrineEntityManagerInterface $entityManagerSessionInterface $sessionMailerInterface $mailer): Response
  4724.     {
  4725.         
  4726.         $fluxos_abertos $entityManager
  4727.             ->getRepository(Fluxo::class)
  4728.             ->fluxosAbertosComMaiorPrazo();
  4729.             
  4730.          $fluxos_mes $entityManager
  4731.         ->getRepository(Fluxo::class)
  4732.         ->findMes();
  4733.         $totalFluxos     0;
  4734.         $clientesUnicos  = [];
  4735.         $totalCaixas     0;
  4736.         $totalDocumentos 0;
  4737.         $totalImagens    0;
  4738.         foreach ($fluxos_mes as $fluxo) {
  4739.             $totalFluxos++;
  4740.             // 👇 garante cliente único
  4741.             if ($fluxo->getCliente()) {
  4742.                 $clienteId $fluxo->getCliente()->getId();
  4743.                 $clientesUnicos[$clienteId] = true;
  4744.             }
  4745.             foreach ($fluxo->getCaixas() as $caixa) {
  4746.                 $totalCaixas++;
  4747.                 foreach ($caixa->getDocumentos() as $documento) {
  4748.                     $totalDocumentos++;
  4749.                     $totalImagens += $documento->getQtd();
  4750.                 }
  4751.             }
  4752.         }
  4753.         $formatter = new \IntlDateFormatter(
  4754.             'pt_BR',
  4755.             \IntlDateFormatter::NONE,
  4756.             \IntlDateFormatter::NONE,
  4757.             'America/Sao_Paulo',
  4758.             \IntlDateFormatter::GREGORIAN,
  4759.             'MMMM'
  4760.         );
  4761.         $nomeMes ucfirst($formatter->format(new \DateTime()));
  4762.         $resumo = [
  4763.             'fluxos'     => $totalFluxos,
  4764.             'clientes'   => count($clientesUnicos), // ✅ não duplica
  4765.             'caixas'     => $totalCaixas,
  4766.             'documentos' => $totalDocumentos,
  4767.             'imagens'    => $totalImagens,
  4768.             'nomeMes'     => $nomeMes
  4769.         ];
  4770.         
  4771.         $a = [];
  4772.         foreach ($fluxos_abertos as $item) {
  4773.             $fluxo $item[0];
  4774.             $maiorData $item['prazo'];
  4775.             $cx 0;
  4776.             $doc 0;
  4777.             $img 0;
  4778.             $cliente_id $fluxo->getCliente()->getId();
  4779.             $cliente $doctrine->getRepository(Cliente::class)
  4780.             ->createQueryBuilder('c')
  4781.             ->where('c.id = :id')
  4782.             ->setParameter('id'$cliente_id)
  4783.             ->getQuery()
  4784.             ->getOneOrNullResult();
  4785.             foreach ($fluxo->getCaixas() as $caixas) {
  4786.                 $cx++;
  4787.                 foreach ($caixas->getDocumentos() as $docs) {
  4788.                     $doc++;
  4789.                     $img += $docs->getQtd();
  4790.                 }
  4791.             }
  4792.             $a[] = [
  4793.                 'fluxo'       => $fluxo->getId(),
  4794.                 'cliente'     => $cliente->getNome(),
  4795.                 'caixas'      => $cx,
  4796.                 'documentos'  => $doc,
  4797.                 'imagens'     => $img,
  4798.                 'prazo'       => $maiorData,
  4799.             ];
  4800.         }
  4801.                 
  4802.         return $this->render('index/metas_fluxos.html.twig', [
  4803.             'data'=>$a,
  4804.             'resumo'=>$resumo
  4805.     
  4806.         ]);
  4807.     }
  4808.     
  4809.     public function configureDashboard(): Dashboard
  4810.     {
  4811.         return Dashboard::new()
  4812.             ->setTitle('IndexDoc')
  4813.             ->setFaviconPath('./img/icon.png');   
  4814.     }
  4815.     
  4816.     public function configureMenuItems(): iterable
  4817.     {
  4818.         // yield MenuItem::linkToDashboard('Dashboard', 'fa fa-home');
  4819.         // yield MenuItem::linkToCrud('The Label', 'fas fa-list', EntityClass::class);
  4820.     }
  4821. }