src/Controller/Admin/DashboardController.php line 129

  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. use App\Service\DriveToOneDriveService;
  53. use Symfony\Contracts\Cache\CacheInterface;
  54. use Symfony\Contracts\Cache\ItemInterface;
  55. use App\Repository\DocumentoRepository;
  56. use App\Repository\TipoRepository;
  57. use App\Repository\ClassificacaoRepository;
  58. use App\Repository\CaixaRepository;
  59. class DashboardController extends AbstractDashboardController
  60. {
  61.     
  62.     #[Route('/', name: 'inicial')]
  63.     public function home(): Response
  64.     {
  65.         
  66.         return $this->redirectToRoute('home');
  67.     }
  68.     
  69.     #[Route('/login_sucess', name: 'login_sucess')]
  70.     public function login_sucess(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager): Response
  71.     {
  72.         
  73.     
  74.         $user_logado = $this->getUser();
  75.         $enabled = $user_logado->getEnabled();
  76.         if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
  77.             $ip_cliente = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0];
  78.         } else {
  79.             $ip_cliente = $_SERVER['REMOTE_ADDR'];
  80.         }
  81.         
  82.           if($enabled == false){
  83.             $error ="Tentativa de login de usuário desativado";
  84.             $user_logado_nome=$user_logado->getNome();
  85.             $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  86.             $registro = new Registro();
  87.             $registro->setOperacao($error);
  88.             $registro->setUser($user_logado_nome);
  89.             $registro->setData($hoje);
  90.             $registro->setIp($ip_cliente);
  91.             $entityManager->persist($registro);
  92.             $entityManager->flush();
  93.             return $this->redirectToRoute('app_logout');
  94.         }
  95.         
  96.         
  97.         
  98.         
  99.         $error ="Login Realizado";
  100.         $user_logado_nome=$user_logado->getNome();
  101.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  102.         $registro = new Registro();
  103.         $registro->setOperacao($error);
  104.         $registro->setUser($user_logado_nome);
  105.         $registro->setData($hoje);
  106.         $registro->setIp($ip_cliente);
  107.         $entityManager->persist($registro);
  108.         $entityManager->flush();
  109.         
  110.       
  111.         
  112.         
  113.         return $this->redirectToRoute('home');     
  114.     }
  115.     
  116.     #[Route('/index/home', name: 'home')]
  117.     public function inicial(PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer): Response
  118.     {
  119.         $user_logado = $this->getUser();
  120.         $user_logado_id = $user_logado->getId();
  121.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  122.         $erro = '';
  123.         $pagina = 'home';
  124.         $p ='';
  125.         
  126.         $etapas  = null;
  127.         if(isset($_POST["btn_cliente"])){
  128.             
  129.             $session->set('cliente_id', $_POST["btn_cliente"]);
  130.             return $this->redirectToRoute('home');
  131.         }
  132.         
  133.         $clienteId = $session->get('cliente_id');
  134.         
  135.         $etapas = $doctrine->getRepository(Etapa::class)->findByUserAndUpdatedAt($user_logado);
  136.         
  137.        
  138.         return $this->render('index/index6.html.twig', [
  139.     
  140.             
  141.             'p'=>$p,
  142.             'erro'=>$erro,
  143.             'pagina' => $pagina,
  144.             'etapas'=>$etapas,
  145.             'cliente' => $cliente,
  146.             'clienteId' => $clienteId
  147.             
  148.             
  149.         ]);
  150.     } 
  151.     #[Route('/index/troca', name: 'troca')]
  152.     public function troca(SessionInterface $session): Response
  153.     {
  154.        
  155.         $session->remove('cliente_id');
  156.         $session->invalidate();
  157.         return $this->redirectToRoute('home');
  158.     }
  159.     #[Route('/index/export', name: 'export')]
  160.     public function export(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session,MessageBusInterface $bus): Response
  161.     {
  162.         
  163.         
  164.         $pendingMessages = $entityManager->getRepository(MessengerMessages::class)->countPendingMessages();
  165.         
  166.         #dd($pendingMessages);
  167.         
  168.         $user_logado = $this->getUser();
  169.         $user_logado_id = $user_logado->getId();
  170.         $userId = $user_logado_id;
  171.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  172.         $dotenv = new Dotenv();
  173.         $dotenv->load(__DIR__.'/.env');
  174.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  175.         $hoje_formt=$hoje->format('Y-m-d') ;
  176.         $doc = $entityManager->getRepository(Documento::class)->findByUserAndDate($user_logado_id, $hoje_formt);
  177.         $dia_prod = 'de hoje';
  178.         
  179.    
  180.         if(isset($_POST["date_perio"])){
  181.             
  182.             
  183.             $startDate = $_POST["de"];
  184.             $endDate = $_POST["ate"];
  185.        
  186.             $de = new \DateTimeImmutable($startDate);
  187.             $ate = new \DateTimeImmutable($endDate);
  188.             $de_formt=$de->format('d/m/Y') ;
  189.             $ate_formt=$ate->format('d/m/Y') ;
  190.             
  191.             if($endDate != ""){ 
  192.                 
  193.                 $doc = $entityManager->getRepository(Documento::class)->findByUserAndDateRange($user_logado_id, $startDate, $endDate);
  194.                 $dia_prod = 'de '. $de_formt.' até '.$ate_formt; 
  195.             
  196.             }
  197.             if($endDate == ""){ 
  198.                 
  199.                 $doc = $entityManager->getRepository(Documento::class)->findByUserAndDate($user_logado_id, $startDate);
  200.                 $dia_prod = 'de '. $de_formt; 
  201.             }
  202.             
  203.             
  204.         }
  205.         
  206.         if(isset($_POST["btn_cliente"])){
  207.             
  208.             $session->set('cliente_id', $_POST["btn_cliente"]);
  209.             return $this->redirectToRoute('home');
  210.         }
  211.         $clienteId = $session->get('cliente_id');
  212.         
  213.         
  214.         
  215.         if ($clienteId == null ) {
  216.             
  217.             $caixas =  "";
  218.             $index_all ="";
  219.             $documentos="";
  220.             $cliente_session = "";
  221.             $cliente_alls = "";
  222.        
  223.         } else {
  224.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  225.             $caixas = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  226.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  227.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  228.             $cliente_alls = $cliente_session->getClienteAll()->getId();
  229.         }
  230.         $erro = '';
  231.         $ii=0;
  232.         $pagina = 'export';
  233.         $p = '';
  234.         $link = '';
  235.         $mx = 0;
  236.         $xy = 0 ; 
  237.         $yz = 0 ; 
  238.         $ay = 0 ;
  239.         $ky = 0 ;
  240.         $pdf ='';
  241.         $pagina_h4 ='Documento(s) para indexar';
  242.         $nome_menu_ = '';
  243.         $index_tipo='';
  244.         
  245.         $user = $this->getUser();
  246.         $user_nome= $user->getEmail();
  247.         $user_nome_name= $user->getNome();
  248.         $pasta_user=$user_nome.'/';
  249.         $arr = [];
  250.         $arrr=0;
  251.         $index_find = null;
  252.         $dt = '';
  253.         $clientS3 = new  S3Client([
  254.             'region'  => 'sa-east-1',
  255.             'version' => 'latest',
  256.             'credentials' => [ 
  257.                 'key'    => $_ENV['AWS_KEY'],
  258.                 'secret' => $_ENV['AWS_SECRET'],
  259.             ],
  260.         ]);
  261.         
  262.        if (isset($_POST["botao_export"])) {
  263.             $caixaId = $_POST["caixas"];
  264.             $caixa_id = $doctrine->getRepository(Caixa::class)->find($_POST["caixas"]);
  265.             $cliente_id = $doctrine->getRepository(Cliente::class)->find($clienteId);
  266.             $clientes_status= $cliente_id->getExtraFields();
  267.             if(!$clientes_status){
  268.                 $clientes_status="ged";
  269.             }
  270.             $cliente_nome = $cliente_id->getNome();
  271.             $clientes = $cliente_id->getId();
  272.             $conteiner = $_POST["conteiner"];
  273.             $cont_file = 0;
  274.             $umlautString = $cliente_nome;
  275.             $slugger = new AsciiSlugger();
  276.             $teste = $slugger->slug($umlautString, $seperator = '-')->toString();
  277.             $caminho = strtolower($teste . '/');
  278.             if ($clientes == 14) { $caminho = 'cartorio-1deg-oficio-de-volta-redonda-rj/'; }
  279.             if ($clientes == 83) { $caminho = 'casf-corretora-apolice-diversos/'; }
  280.             if ($clientes == 35) { $caminho = 'pmecj-sp-saude/'; }
  281.             if ($clientes == 107) { $caminho = 'pmecj-sp-execucao-fiscal/'; }
  282.             if ($clientes == 4) { $caminho = 'cartorio-souza-reis-barra-mansa/'; }
  283.             if ($clientes == 112) { $caminho = 'saae-cartao-de-ponto/'; }
  284.             if ($clientes == 15) { $caminho = 'cbsi-dossies/'; }
  285.             if ($clientes == 55) { $caminho = 'casf-gerep-contratos-de-prestadores-de-saude-pj/'; }
  286.             if ($clientes == 13) { $caminho = 'casa-de-saude-santa-maria-c-s-s.M/'; }
  287.             if ($clientes == 40) { $caminho = 'fasf-atas-e-diarios/'; }
  288.         
  289.             $filesTmp  = $_FILES['file']['tmp_name'];
  290.             $filesName = $_FILES['file']['name'];
  291.             
  292.             foreach ($filesTmp as $index => $file) {
  293.             
  294.                 $uuid = Uuid::v4();
  295.                 $cont_file++;
  296.                 
  297.                 
  298.                 // nome original do arquivo
  299.                 $originalName = pathinfo($filesName[$index], PATHINFO_FILENAME);
  300.                 
  301.                 // sanitiza o nome (remove acentos, espaços estranhos etc.)
  302.                 $slugger = new AsciiSlugger();
  303.                 $safeName = strtolower($slugger->slug($originalName)->toString());
  304.                 
  305.                 // 🔹 Se cliente for local, usa nome original
  306.                 if ($clientes_status === 'local') {
  307.             
  308.             
  309.                     $filename = $safeName . '.pdf';
  310.             
  311.                 } else {
  312.                     if ($cliente_alls === 42) {
  313.                          $filename = $originalName . '.pdf';
  314.                     }else{
  315.                         $filename = $uuid . '.pdf';
  316.                     }
  317.                 }
  318.             
  319.                 $tempDir = __DIR__ . '/../../var/uploads/messenger';
  320.                 if (!is_dir($tempDir)) {
  321.                     mkdir($tempDir, 0777, true);
  322.                 }
  323.             
  324.                 $tempFilePath = $tempDir . '/' . $filename;
  325.             
  326.                 move_uploaded_file($file, $tempFilePath);
  327.                 chmod($tempFilePath, 0644);
  328.                 if (!file_exists($tempFilePath) || filesize($tempFilePath) === 0) {
  329.                     throw new \RuntimeException(
  330.                         'Falha ao gravar PDF temporário: ' . $tempFilePath
  331.                     );
  332.                 }
  333.                 
  334.                 // evita race condition de filesystem
  335.                 clearstatcache(true, $tempFilePath);
  336.                 
  337.                 
  338.                 
  339.                 
  340.                 $bus->dispatch(new UploadMultipartMessage(
  341.                     $tempFilePath,
  342.                     $filename,
  343.                     $caminho,
  344.                     '',
  345.                     $caixaId,
  346.                     $clienteId,
  347.                     $userId,
  348.                     0,
  349.                     $conteiner,
  350.                     $clientes,
  351.                     $clientes_status,
  352.                     $safeName,
  353.                     $originalName,
  354.                     $cliente_alls
  355.                 ));
  356.             }
  357.         
  358.             $log = new Registro();
  359.             $log->setOperacao('EXPORTOU ' . $cont_file . ' DOCUMENTO(S)');
  360.             $log->setUser($user_nome_name);
  361.             $log->setCliente($cliente_nome);
  362.             $entityManager->persist($log);
  363.             $entityManager->flush();
  364.         
  365.             return $this->redirectToRoute('export');
  366.         }
  367.       
  368.         return $this->render('index/index.html.twig', [
  369.             'documentos' => $documentos,
  370.             'xy' => $xy,
  371.             'yz' => $yz,
  372.             'ay'=>$ay,
  373.             'link' => $link,
  374.             'pdf'=>$pdf,
  375.             'p'=>$p,
  376.             'erro'=>$erro,
  377.             'index_all'=>$index_all,
  378.             'index_tipo'=>$index_tipo,
  379.             'ky'=>$ky,
  380.             'pagina' => $pagina,
  381.             'pagina_h4' =>$pagina_h4,
  382.             'index_find'=>$index_find,
  383.             'mx'=>$mx,
  384.             'caixas' => $caixas,
  385.             'user_logado' => $user_logado,
  386.             'cliente' => $cliente,
  387.             'cliente_session' => $cliente_session,
  388.             'doc'=>$doc,
  389.             'dia_prod' => $dia_prod
  390.         ]);
  391.     }
  392.     
  393.     #[Route('/index/planilha', name: 'planilha')]
  394.     public function planilha(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session): Response
  395.     {
  396.         
  397.       
  398.         $form = $this->createForm(UploadType::class);
  399.         $user_logado= $this->getUser();
  400.         $user_logado_id = $user_logado->getId();
  401.         $user_nome_name= $user_logado->getNome();
  402.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  403.         $form->handleRequest($request);
  404.         $dotenv = new Dotenv();
  405.         $dotenv->load(__DIR__.'/.env');
  406.         $erro = '';
  407.         $excel = 0;
  408.         $pagina = 'index';
  409.         $p = '';
  410.         $clientS3 = new  S3Client([
  411.             'region'  => 'sa-east-1',
  412.             'version' => 'latest',
  413.             'credentials' => [ 
  414.                 'key'    => $_ENV['AWS_KEY'],
  415.                 'secret' => $_ENV['AWS_SECRET'],
  416.             ],
  417.         ]);
  418.    
  419.         
  420.         
  421.         if(isset($_POST["btn_cliente"])){
  422.             
  423.             $session->set('cliente_id', $_POST["btn_cliente"]);
  424.             return $this->redirectToRoute('home');
  425.         }
  426.         $clienteId = $session->get('cliente_id');
  427.         
  428.         
  429.         
  430.         if ($clienteId == null ) {
  431.             
  432.             $caixas =  "";
  433.             $index_all ="";
  434.             $documentos="";
  435.             $cliente_session = "";
  436.        
  437.         } else {
  438.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  439.             $caixas = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  440.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  441.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  442.             $cliente_nome= $cliente_session->getNome();
  443.             
  444.         }
  445.         
  446.         
  447.        
  448.         
  449.       
  450.         if ($form->isSubmitted() && $form->isValid()) {
  451.             $list =[];
  452.             $file = $form['file']->getData();
  453.             $spreadsheet = IOFactory::load($file->getPathname());
  454.             $sheetData = $spreadsheet->getActiveSheet()->toArray();
  455.             foreach ($sheetData as $row) {
  456.                 $excel ++;
  457.                 $id_cx = null ;
  458.                 $selections = $_POST["selections"];
  459.                 $nome = array_search('0', $selections);
  460.                 $caixa = array_search('1', $selections);
  461.                 $assunto = array_search('2', $selections);
  462.                 $keywod = array_search('3', $selections);
  463.                 $data_documento = array_search('4', $selections);
  464.                 $data_vecimento = array_search('5', $selections);
  465.                 $descricao  = array_search('6', $selections);
  466.                 if ($caixa != false ) {
  467.                         
  468.                     
  469.                     $numerosExcel = preg_replace('/\D/', '', $row[$caixa]);
  470.                     foreach ($caixas as $key) {
  471.                         $nome_cx = $key->getNome();
  472.                         $numerosCaixa = preg_replace('/\D/', '', $nome_cx);
  473.                         if ($numerosCaixa == $numerosExcel ) {
  474.                             
  475.                                 $id_cx = $key->getId();
  476.                         }
  477.                     }
  478.                     
  479.                     
  480.                     if ($id_cx == null) {
  481.                         echo '<script>alert("ERRO NA LINHA '.$excel.' NÃO EXISTE ESSA CAIXA CADASTRADA")</script>';
  482.                             return $this->render('index/index2.html.twig', [
  483.                             'documentos' => $documentos,
  484.                             'p'=>$p,
  485.                             'erro'=>$erro,
  486.                             'index_all'=>$index_all,
  487.                             'pagina' => $pagina,
  488.                             'caixas' => $caixas,
  489.                             'user_logado' => $user_logado,
  490.                             'cliente' => $cliente,
  491.                             'cliente_session' => $cliente_session,
  492.                             'form' => $form->createView(),
  493.                                             ]);
  494.                     }
  495.                 }
  496.                 
  497.                 
  498.                     $yourEntity = new Documento();
  499.                     // Ajuste conforme necessário
  500.                     $yourEntity->setUser($user_logado);
  501.                     $yourEntity->setCliente($cliente_session);
  502.                     $yourEntity->setClassificacao($doctrine->getRepository(Classificacao::class)->find(1));
  503.                     $yourEntity->setTipo($doctrine->getRepository(Tipo::class)->find($_POST["tipo"]));
  504.                     $yourEntity->setNome($row[$nome]); 
  505.                     if ($assunto != false ) {$yourEntity->setAssunto($row[$assunto]);}
  506.                     if ($caixa != false ) {$yourEntity->setCaixa($doctrine->getRepository(Caixa::class)->find($id_cx));}
  507.                     if ($keywod != false ) {$yourEntity->setKeywords($row[$keywod]);}
  508.                     
  509.                     if ($data_documento != false ) {
  510.                         if (!empty(trim($row[$data_documento])) && strtoupper(trim($row[$data_documento])) !== "NULL") {
  511.                             $yourEntity->setDataDocumento(new \DateTimeImmutable($row[$data_documento]));
  512.                         }
  513.                     }
  514.                     if ($data_vecimento != false ) {
  515.                         if (!empty(trim($row[$data_vecimento])) && strtoupper(trim($row[$data_vecimento])) !== "NULL") {
  516.                             $yourEntity->setVencimentoDocumento(new \DateTimeImmutable($row[$data_vecimento]));
  517.                         }
  518.                     }
  519.                     if ($descricao != false ) {$yourEntity->setExtraFields($row[$descricao]);}
  520.                     $entityManager->persist($yourEntity);
  521.                     $entityManager->flush();
  522.                     $erro = "ok";
  523.                     
  524.                    
  525.                     
  526.             }
  527.                 
  528.                 $log = new Registro();
  529.                 $log->setOperacao('PLANILHA EXPORTADA, '.$excel .' CADASTROS INSERIDOS.' ); 
  530.                 $log->setUser($user_nome_name);
  531.                 $log->setCliente($cliente_nome);
  532.                 $entityManager->persist($log);
  533.                 $entityManager->flush();
  534.                 $erro = "ok";
  535.                 if ($excel>1)  {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTROS INSERIDOS , .' ;}
  536.                 if ($excel==1) {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTRO INSERIDO ,' ;}
  537.             
  538.         }
  539.         
  540.         return $this->render('index/index2.html.twig', [
  541.                             'documentos' => $documentos,
  542.                             'p'=>$p,
  543.                             'erro'=>$erro,
  544.                             'index_all'=>$index_all,
  545.                             'pagina' => $pagina,
  546.                             'caixas' => $caixas,
  547.                             'user_logado' => $user_logado,
  548.                             'cliente' => $cliente,
  549.                             'cliente_session' => $cliente_session,
  550.                             'form' => $form->createView(),
  551.                                             ]);
  552.        
  553.     }
  554.     
  555.     #[Route('/index/planilha/classificacao', name: 'planilha_classificacao')]
  556.     public function planilha_classificacao(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session): Response
  557.     {
  558.         
  559.       
  560.         $form = $this->createForm(UploadType::class);
  561.         $user_logado= $this->getUser();
  562.         $user_logado_id = $user_logado->getId();
  563.         $user_nome_name= $user_logado->getNome();
  564.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  565.         $form->handleRequest($request);
  566.         $erro = '';
  567.         $excel = 0;
  568.         $pagina = 'index';
  569.         $p = '';
  570.         if(isset($_POST["btn_cliente"])){
  571.             
  572.             $session->set('cliente_id', $_POST["btn_cliente"]);
  573.             return $this->redirectToRoute('home');
  574.         }
  575.         $clienteId = $session->get('cliente_id');
  576.         
  577.         
  578.         
  579.         if ($clienteId == null ) {
  580.             
  581.             $caixas =  "";
  582.             $cliente_session = "";
  583.        
  584.         } else {
  585.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  586.             $cliente_nome= $cliente_session->getNome();  
  587.         }
  588.         
  589.         
  590.        
  591.         
  592.       
  593.         if ($form->isSubmitted() && $form->isValid()) {
  594.             $list =[];
  595.             $file = $form['file']->getData();
  596.             $spreadsheet = IOFactory::load($file->getPathname());
  597.             $sheetData = $spreadsheet->getActiveSheet()->toArray();
  598.             foreach ($sheetData as $row) {
  599.                 $excel ++;
  600.                 $id_cx = null ;
  601.                 $selections = $_POST["selections"];
  602.                 $nome = array_search('0', $selections);
  603.                 $fase_corrente = array_search('1', $selections);
  604.                 $fase_intermediaria = array_search('2', $selections);
  605.                 $destinacao_final = array_search('3', $selections);
  606.                 $observacoes = array_search('4', $selections);
  607.                 $descricao = array_search('5', $selections);
  608.                 
  609.                 
  610.                 if($row[$nome] != null){
  611.                 
  612.                     $yourEntity = new Classificacao();
  613.                     $yourEntity->setNome($row[$nome]);
  614.                     $yourEntity->setFaseCorrente($row[$fase_corrente]);
  615.                     $yourEntity->setFaseIntermediaria($row[$fase_intermediaria]);
  616.                     $yourEntity->setDestinacaoFinal($row[$destinacao_final]);
  617.                     $yourEntity->setObservacoes($row[$observacoes]);
  618.                     $yourEntity->setExtraFields($row[$descricao]);
  619.                     $yourEntity->setCliente($cliente_session);
  620.                     $entityManager->persist($yourEntity);
  621.                     $entityManager->flush();
  622.                     $erro = "ok";
  623.                 }
  624.                
  625.                     
  626.                    
  627.                     
  628.             }
  629.                 
  630.             $log = new Registro();
  631.             $log->setOperacao('PLANILHA EXPORTADA, '.$excel .' CADASTROS INSERIDOS.' ); 
  632.             $log->setUser($user_nome_name);
  633.             $log->setCliente($cliente_nome);
  634.             $entityManager->persist($log);
  635.             $entityManager->flush();
  636.             $erro = "ok";
  637.             if ($excel>1)  {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTROS INSERIDOS , .' ;}
  638.             if ($excel==1) {$p =  'PLANILHA EXPORTADA COM SUCESSO, '.$excel .' CADASTRO INSERIDO ,' ;}
  639.             
  640.         }
  641.         
  642.         return $this->render('index/index_classificao.html.twig', [
  643.                             'p'=>$p,
  644.                             'erro'=>$erro,
  645.                             'pagina' => $pagina,
  646.                             'user_logado' => $user_logado,
  647.                             'cliente' => $cliente,
  648.                             'cliente_session' => $cliente_session,
  649.                             'form' => $form->createView(),
  650.                                             ]);
  651.        
  652.     }
  653.     #[Route('/index/indexacao', name: 'index')]
  654.     public function indexar(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager , SessionInterface $session): Response
  655.     {
  656.         $dotenv = new Dotenv();
  657.         $dotenv->load(__DIR__.'/.env');
  658.         $user_logado = $this->getUser();
  659.         $form = $this->createForm(UploadType::class);
  660.         $form->handleRequest($request);
  661.         $user_logado_tipoAcesso = $user_logado->getTipoAcesso();
  662.         $user_logado_nome = $user_logado->getNome();
  663.         $user_logado_id = $user_logado->getId();
  664.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  665.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  666.         $hoje_formt=$hoje->format('Y-m-d');
  667.         $doc = $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome, $hoje_formt);
  668.         $dia_prod = 'de hoje';
  669.         $permissao = [];
  670.         $list_indexador = [];
  671.          
  672.         if(isset($_POST["btn_cliente"])){
  673.             
  674.             $session->set('cliente_id', $_POST["btn_cliente"]);
  675.             return $this->redirectToRoute('home');
  676.         }
  677.         $clienteId = $session->get('cliente_id');
  678.         if ($clienteId == null ) {
  679.             
  680.             $caixas =  "";
  681.             $index_all ="";
  682.             $documentos="";
  683.             $cliente_session = "";
  684.        
  685.         } else {
  686.             
  687.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  688.             $caixas = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  689.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  690.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  691.             
  692.             
  693.         }
  694.        
  695.         if(isset($_POST["date_perio"])){
  696.             
  697.             
  698.             $startDate = $_POST["de"];
  699.             $endDate = $_POST["ate"];
  700.        
  701.             $de = new \DateTimeImmutable($startDate);
  702.             $ate = new \DateTimeImmutable($endDate);
  703.             $de_formt=$de->format('d/m/Y') ;
  704.             $ate_formt=$ate->format('d/m/Y') ;
  705.             
  706.             if($endDate != ""){ 
  707.                 
  708.                 $doc = $entityManager->getRepository(Documento::class)->findByUserAndDateIndexRange($user_logado_nome, $startDate, $endDate);
  709.                 $dia_prod = 'de '. $de_formt.' até '.$ate_formt; 
  710.             
  711.             }
  712.             if($endDate == ""){ 
  713.                 
  714.                 $doc = $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome, $startDate);
  715.                 $dia_prod = 'de '. $de_formt; 
  716.             }
  717.             
  718.             
  719.             
  720.         }
  721.        
  722.         
  723.         foreach ($user_logado_tipoAcesso["new"] as  $value) {
  724.             
  725.             foreach ($index_all as $key) {
  726.                 if ( $key->getId() ==  $value) {
  727.                     
  728.                     $permissao[] = $value;
  729.                     
  730.                 }
  731.                
  732.             }
  733.         }
  734.     
  735.         $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null , 'cliente' => $clienteId]);
  736.         
  737.         $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $clienteId]);
  738.         $cliente_id = $doctrine->getRepository(Cliente::class)->findBy(['id' => $clienteId]);
  739.         
  740.        
  741.         
  742.         
  743.         foreach ($cliente_id as $cliente_ids) {
  744.             
  745.             $cliente_nome= $cliente_ids->getNome();
  746.             $clientes= $cliente_ids->getId();
  747.             $umlautString =$cliente_nome;
  748.             $slugger = new AsciiSlugger();
  749.             $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  750.             $caminho = strtolower ($teste.'/');
  751.                         
  752.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  753.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  754.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  755.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  756.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  757.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  758.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  759.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  760.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  761.         }
  762.         
  763.         
  764.         
  765.         if ($clienteId == null ) {
  766.             
  767.             $caixas =  "";
  768.        
  769.         } else {
  770.             
  771.             $caixas = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  772.         }   
  773.             
  774.            
  775.         $erro = '';
  776.         $ii=0;
  777.         $pagina = 'index';
  778.         $p = '';
  779.         $link = '';
  780.         $mx = 0;
  781.         $xy = 0 ; 
  782.         $yz = 0 ; 
  783.         $ay = 0 ;
  784.         $ky = 0 ;
  785.         $pdf ='';
  786.         $pagina_h4 ='Documento(s) para indexar';
  787.         $nome_menu_ = '';
  788.         $index_tipo='';
  789.         $uuid = Uuid::v4();
  790.         $user = $this->getUser();
  791.         $user_nome= $user->getEmail();
  792.         $user_nome_name= $user->getNome();
  793.         $pasta_user=$user_nome.'/';
  794.         $arr = [];
  795.         $arrr=0;
  796.         $index_find = null;
  797.         $dt = '';
  798.         $clientS3 = new  S3Client([
  799.                     'region'  => 'sa-east-1',
  800.                     'version' => 'latest',
  801.                     'credentials' => [ 
  802.                         'key'    => $_ENV['AWS_KEY'],
  803.                         'secret' => $_ENV['AWS_SECRET'],
  804.                     ],
  805.                 ]);
  806.         
  807.      
  808.             
  809.         if(isset($_POST["dt"]))
  810.         {   
  811.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => $_POST["dt"]]);
  812.             $index_find =  $doctrine->getRepository(Tipo::class)->find($_POST["dt"]);
  813.             $pagina =$index_find->getNome();
  814.             $pagina_h4 ='Documento(s) do tipo ( '.$pagina.' )';
  815.             
  816.             
  817.         }
  818.        
  819.         if(isset($_POST["botao_index"])){
  820.             
  821.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  822.             $link = $pdf->getImage();
  823.             $xy = 1 ;
  824.             
  825.         }
  826.         if(isset($_POST["botao_doc"])){
  827.             
  828.             
  829.             $yz = 0 ;
  830.             $xy = 1 ;
  831.             $ay = 1 ;
  832.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  833.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  834.            
  835.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  836.             $index_tipo_tipo =  $index_tipo->getNome();
  837.             $link = $pdf->getImage();
  838.             $fase=$_POST["fase"];
  839.             $data = $_POST["data"];
  840.             $cx = $_POST["caixas"];
  841.             $classifica = $_POST["classifica"];
  842.             $fase = $_POST["fase"];
  843.             $desc = $_POST["desc"];
  844.             $assunto = $_POST["assunto"];
  845.             $chave = $_POST["chave"];
  846.             $nome = $_POST["nome"];
  847.             $conteiner = $_POST["conteiner"];
  848.             
  849.           
  850.             
  851.             $caixa_id = $doctrine->getRepository(Caixa::class)->find($cx);
  852.             
  853.             
  854.             
  855.             // Encontra todos os números na frase
  856.             preg_match_all('/\d+/', $fase, $matches);
  857.             // $matches[0] agora contém todos os números encontrados na frase
  858.             $numeros = array_map('intval', $matches[0]);
  859.             // Exibe os números encontrados
  860.             
  861.             if ($clientes != 7) {
  862.            
  863.                 if ($data != "") {
  864.                     
  865.                     if ($fase != "") {
  866.     
  867.                         // Número inteiro que você deseja somar ao ano
  868.                         $numeroParaSomar = $numeros[0];
  869.     
  870.                         // Extrair o ano da data
  871.                         list($ano, $mes, $dia) = explode('-', $data);
  872.     
  873.                         // Converter o ano para um número inteiro
  874.                         $ano = intval($ano);
  875.     
  876.                         // Somar o número ao ano
  877.                         $data_vecimento =  $ano + $numeroParaSomar.'-'.$mes.'-'. $dia;
  878.     
  879.                         $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  880.     
  881.                     }
  882.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  883.                 }
  884.             }    
  885.             
  886.             if ($clientes == 7) {
  887.                   
  888.                   $pdf->setVencimentoDocumento(new \DateTimeImmutable($fase));
  889.                   $pdf->setDataDocumento(new \DateTimeImmutable($data));
  890.              }
  891.              
  892.             $pdf->setAssunto($assunto);
  893.             if ($classifica != "") {
  894.                 $classifica_id = $doctrine->getRepository(Classificacao::class)->find($classifica);
  895.                 $pdf->setClassificacao($classifica_id);
  896.             }
  897.             $pdf->setCaixa($caixa_id);
  898.             $pdf->setExtraFields($desc);
  899.             $pdf->setNome($nome);
  900.             $pdf->setKeywords($chave);
  901.             $pdf->setUserIndex($user_nome_name);
  902.             $pdf->setConteiner($conteiner);
  903.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  904.             $pdf->setTipo($index_tipo);
  905.             $entityManager->flush();
  906.             $id_pd = $pdf->getId();    
  907.             $log = new Registro();
  908.             $log->setOperacao('Indexou o Documento com id '.$id_pd); 
  909.             $log->setUser($user_nome_name);
  910.             $log->setCliente($cliente_nome);
  911.             $entityManager->persist($log);
  912.             $entityManager->flush();
  913.             $erro = 'ok';
  914.             $p =  $index_tipo_tipo.' indexado com sucesso';
  915.             
  916.            
  917.             
  918.            
  919.         }   
  920.         if(isset($_POST["botao_index_edit"])){
  921.             
  922.             $yz = 0 ;
  923.             $xy = 1 ;
  924.             $ay = 1 ;
  925.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  926.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  927.             $link = $pdf->getImage();
  928.         }
  929.         if(isset($_POST["botao_volta"])){
  930.             $xy = 0 ;
  931.             $yz = 0 ;
  932.         }
  933.         if(isset($_POST["index_button"])){
  934.             
  935.             
  936.             $yz = 0 ;
  937.             $xy = 1 ;
  938.             $ay = 1 ;
  939.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  940.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["index_button"]);
  941.             $link = $pdf->getImage();
  942.         }
  943.         if(isset($_POST["botao_cancel"])){
  944.             $yz = 0 ;
  945.             $xy = 1 ;
  946.             $ay = 0 ;
  947.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  948.             $link = $pdf->getImage();
  949.             
  950.         }
  951.         if(isset($_POST["delet"])){
  952.            
  953.             $ky = 1 ;
  954.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["delet"]);
  955.             $documentos = $doctrine->getRepository(Documento::class)->findBy(['id' => $_POST["delet"]]);
  956.             
  957.             if($pdf->getTipo()!= null){
  958.                 $index_find =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  959.                 $pagina =$index_find->getTipo();
  960.                 $pagina_h4 ='Documento(s) do tipo ( '.$index_find->getTipo().' )';
  961.             }
  962.                         
  963.         }
  964.         if(isset($_POST["delet_cancel"])){
  965.             $ky = 0 ;
  966.         }
  967.         if(isset($_POST["delet_sim"])){
  968.             
  969.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  970.             $id_pd = $pdf->getId();
  971.             $entityManager->remove($pdf);
  972.             $entityManager->flush();
  973.           
  974.             $log = new Registro();
  975.             $log->setOperacao('Excluiu Documento com id '.$id_pd); 
  976.             $log->setUser($user_nome_name);
  977.             $log->setCliente($cliente_nome);
  978.             $entityManager->persist($log);
  979.             $entityManager->flush();
  980.             $erro = 'ok';
  981.             $p = 'Documento com id '.$id_pd.' excluido com sucesso '; 
  982.         }
  983.         if(isset($_POST["index_edit"])){
  984.             $yz = 0 ;
  985.             $xy = 1 ;
  986.             $ay = 2 ;
  987.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  988.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  989.             $link = $pdf->getImage();
  990.         }
  991.        
  992.        
  993.         $cmd = $clientS3->getCommand('GetObject', [
  994.                 'Bucket' => 'arquivosdoc',
  995.                 'Key'    => $caminho. $link, 
  996.             ]);
  997.             
  998.             $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  999.             $all_Url = (string) $req->getUri();
  1000.         return $this->render('index/index1.html.twig', [
  1001.             'documentos' => $documentos,
  1002.             'xy' => $xy,
  1003.             'yz' => $yz,
  1004.             'ay'=>$ay,
  1005.             'link' => $link,
  1006.             'pdf'=>$pdf,
  1007.             'p'=>$p,
  1008.             'erro'=>$erro,
  1009.             'index_all'=>$index_all,
  1010.             'index_tipo'=>$index_tipo,
  1011.             'ky'=>$ky,
  1012.             'pagina' => $pagina,
  1013.             'pagina_h4' =>$pagina_h4,
  1014.             'index_find'=>$index_find,
  1015.             'mx'=>$mx,
  1016.             'caixas' => $caixas,
  1017.             'class' => $class,
  1018.             'permissao'=>$permissao,
  1019.             'caminho' =>$caminho,
  1020.             'clientes' => $clientes,
  1021.             'doc'=>$doc,
  1022.             'dia_prod' => $dia_prod,
  1023.             'cliente_session' => $cliente_session,
  1024.             'all_Url'=>$all_Url
  1025.         ]);
  1026.     }
  1027.     
  1028.     
  1029.     #[Route('/index/corre', name: 'index_corre')]
  1030.     public function index_corre(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager , SessionInterface $session): Response
  1031.     {
  1032.         $dotenv = new Dotenv();
  1033.         $dotenv->load(__DIR__.'/.env');
  1034.         $user_logado = $this->getUser();
  1035.         $form = $this->createForm(UploadType::class);
  1036.         $form->handleRequest($request);
  1037.         $user_logado_tipoAcesso = $user_logado->getTipoAcesso();
  1038.         $user_logado_nome = $user_logado->getNome();
  1039.         $user_logado_id = $user_logado->getId();
  1040.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  1041.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  1042.         $hoje_formt=$hoje->format('Y-m-d');
  1043.         $doc = $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome, $hoje_formt);
  1044.         $dia_prod = 'de hoje';
  1045.         $permissao = [];
  1046.         $list_indexador = [];
  1047.          
  1048.         if(isset($_POST["btn_cliente"])){
  1049.             
  1050.             $session->set('cliente_id', $_POST["btn_cliente"]);
  1051.             return $this->redirectToRoute('home');
  1052.         }
  1053.         $clienteId = $session->get('cliente_id');
  1054.         if ($clienteId == null ) {
  1055.             
  1056.             $caixas =  "";
  1057.             $index_all ="";
  1058.             $documentos="";
  1059.             $cliente_session = "";
  1060.        
  1061.         } else {
  1062.             
  1063.             $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $clienteId]);
  1064.             $caixas = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  1065.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => null ,'cliente' => $clienteId]);
  1066.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);
  1067.             
  1068.             
  1069.         }
  1070.        
  1071.         if(isset($_POST["date_perio"])){
  1072.             
  1073.             
  1074.             $startDate = $_POST["de"];
  1075.             $endDate = $_POST["ate"];
  1076.        
  1077.             $de = new \DateTimeImmutable($startDate);
  1078.             $ate = new \DateTimeImmutable($endDate);
  1079.             $de_formt=$de->format('d/m/Y') ;
  1080.             $ate_formt=$ate->format('d/m/Y') ;
  1081.             
  1082.             if($endDate != ""){ 
  1083.                 
  1084.                 $doc = $entityManager->getRepository(Documento::class)->findByUserAndDateIndexRange($user_logado_nome, $startDate, $endDate);
  1085.                 $dia_prod = 'de '. $de_formt.' até '.$ate_formt; 
  1086.             
  1087.             }
  1088.             if($endDate == ""){ 
  1089.                 
  1090.                 $doc = $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome, $startDate);
  1091.                 $dia_prod = 'de '. $de_formt; 
  1092.             }
  1093.             
  1094.             
  1095.             
  1096.         }
  1097.        
  1098.         
  1099.         foreach ($user_logado_tipoAcesso["new"] as  $value) {
  1100.             
  1101.             foreach ($index_all as $key) {
  1102.                 if ( $key->getId() ==  $value) {
  1103.                     
  1104.                     $permissao[] = $value;
  1105.                     
  1106.                 }
  1107.                
  1108.             }
  1109.         }
  1110.         $ids = [
  1111.             6872304, 6818199, 6869816, 6869252, 6821222, 6869814, 6866863, 6852698,
  1112.             6818244, 6872298, 6826550, 6867034, 6869774, 6868323, 6823222, 6868678,
  1113.             6862719, 6826530, 6819080, 6868011, 6823849, 6868443, 6823107, 6858469,
  1114.             6819006, 6872241, 6872243, 6836508, 6836538, 6823231, 6841051, 6862616,
  1115.             6836483, 6836476, 6823024, 6868690, 6868662, 6867891, 6836582, 6868372,
  1116.             6836482, 6823893, 6872268, 6834758, 6821087, 6867018, 6836503, 6872202,
  1117.             6836479, 6818242, 6863718, 6834830, 6867256, 6872259, 6868597, 6834172,
  1118.             6836492, 6869376, 6818965, 6872168, 6868595, 6860317, 6859908, 6868330,
  1119.             6839939, 6872285, 6869366, 6862659, 6824620, 6869847, 6818237, 6834659,
  1120.             6834917, 6866975, 6869454, 6861937, 6863512, 6834747, 6819937, 6834280,
  1121.             6832406, 6862744, 6818963, 6836480, 6872203, 6818830, 6823892, 6831255,
  1122.             6816562, 6872201, 6831256, 6866999, 6836481, 6868423, 6816568, 6862679,
  1123.             6868314, 6866634, 6839557, 6869243, 6859933, 6869515, 6832578, 6836535,
  1124.             6823855, 6823845, 6823876, 6832397, 6836478, 6863719, 6859935, 6871251,
  1125.             6869513, 6869510, 6835848, 6831156, 6836517
  1126.         ];
  1127.             
  1128.         $qb = $doctrine->getRepository(Documento::class)->createQueryBuilder('d');
  1129.         $documentos = $qb
  1130.             ->where('d.id IN (:ids)')
  1131.             ->andWhere(
  1132.                 $qb->expr()->orX(
  1133.                     'd.extraFields IS NULL',
  1134.                     'd.dataDocumento IS NULL'
  1135.                 )
  1136.             )
  1137.             ->setParameter('ids', $ids)
  1138.             ->getQuery()
  1139.             ->getResult();
  1140.         
  1141.         $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $clienteId]);
  1142.         $cliente_id = $doctrine->getRepository(Cliente::class)->findBy(['id' => $clienteId]);
  1143.         
  1144.        
  1145.         
  1146.         
  1147.         foreach ($cliente_id as $cliente_ids) {
  1148.             
  1149.             $cliente_nome= $cliente_ids->getNome();
  1150.             $clientes= $cliente_ids->getId();
  1151.             $umlautString =$cliente_nome;
  1152.             $slugger = new AsciiSlugger();
  1153.             $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  1154.             $caminho = strtolower ($teste.'/');
  1155.                         
  1156.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  1157.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  1158.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  1159.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  1160.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  1161.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  1162.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  1163.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  1164.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  1165.         }
  1166.         
  1167.         
  1168.         
  1169.         if ($clienteId == null ) {
  1170.             
  1171.             $caixas =  "";
  1172.        
  1173.         } else {
  1174.             
  1175.             $caixas = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($clienteId);
  1176.         }   
  1177.             
  1178.            
  1179.         $erro = '';
  1180.         $ii=0;
  1181.         $pagina = 'index';
  1182.         $p = '';
  1183.         $link = '';
  1184.         $mx = 0;
  1185.         $xy = 0 ; 
  1186.         $yz = 0 ; 
  1187.         $ay = 0 ;
  1188.         $ky = 0 ;
  1189.         $pdf ='';
  1190.         $pagina_h4 ='Documento(s) para indexar';
  1191.         $nome_menu_ = '';
  1192.         $index_tipo='';
  1193.         $uuid = Uuid::v4();
  1194.         $user = $this->getUser();
  1195.         $user_nome= $user->getEmail();
  1196.         $user_nome_name= $user->getNome();
  1197.         $pasta_user=$user_nome.'/';
  1198.         $arr = [];
  1199.         $arrr=0;
  1200.         $index_find = null;
  1201.         $dt = '';
  1202.         $clientS3 = new  S3Client([
  1203.                     'region'  => 'sa-east-1',
  1204.                     'version' => 'latest',
  1205.                     'credentials' => [ 
  1206.                         'key'    => $_ENV['AWS_KEY'],
  1207.                         'secret' => $_ENV['AWS_SECRET'],
  1208.                     ],
  1209.                 ]);
  1210.         
  1211.      
  1212.             
  1213.         if(isset($_POST["dt"]))
  1214.         {   
  1215.             $documentos =  $doctrine->getRepository(Documento::class)->findBy(['tipo' => $_POST["dt"]]);
  1216.             $index_find =  $doctrine->getRepository(Tipo::class)->find($_POST["dt"]);
  1217.             $pagina =$index_find->getNome();
  1218.             $pagina_h4 ='Documento(s) do tipo ( '.$pagina.' )';
  1219.             
  1220.             
  1221.         }
  1222.        
  1223.         if(isset($_POST["botao_index"])){
  1224.             
  1225.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  1226.             $link = $pdf->getImage();
  1227.             $xy = 1 ;
  1228.             
  1229.         }
  1230.         if(isset($_POST["botao_doc"])){
  1231.             
  1232.             
  1233.             $yz = 0 ;
  1234.             $xy = 1 ;
  1235.             $ay = 1 ;
  1236.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  1237.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  1238.            
  1239.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  1240.             $index_tipo_tipo =  $index_tipo->getNome();
  1241.             $link = $pdf->getImage();
  1242.             $fase=$_POST["fase"];
  1243.             $data = $_POST["data"];
  1244.             $cx = $_POST["caixas"];
  1245.             $classifica = $_POST["classifica"];
  1246.             $fase = $_POST["fase"];
  1247.             $desc = $_POST["desc"];
  1248.             $assunto = $_POST["assunto"];
  1249.             $chave = $_POST["chave"];
  1250.             $nome = $_POST["nome"];
  1251.             $conteiner = $_POST["conteiner"];
  1252.             
  1253.           
  1254.             
  1255.             $caixa_id = $doctrine->getRepository(Caixa::class)->find($cx);
  1256.             
  1257.             
  1258.             
  1259.             // Encontra todos os números na frase
  1260.             preg_match_all('/\d+/', $fase, $matches);
  1261.             // $matches[0] agora contém todos os números encontrados na frase
  1262.             $numeros = array_map('intval', $matches[0]);
  1263.             // Exibe os números encontrados
  1264.             
  1265.             if ($clientes != 7) {
  1266.            
  1267.                 if ($data != "") {
  1268.                     
  1269.                     if ($fase != "") {
  1270.     
  1271.                         // Número inteiro que você deseja somar ao ano
  1272.                         $numeroParaSomar = $numeros[0];
  1273.     
  1274.                         // Extrair o ano da data
  1275.                         list($ano, $mes, $dia) = explode('-', $data);
  1276.     
  1277.                         // Converter o ano para um número inteiro
  1278.                         $ano = intval($ano);
  1279.     
  1280.                         // Somar o número ao ano
  1281.                         $data_vecimento =  $ano + $numeroParaSomar.'-'.$mes.'-'. $dia;
  1282.     
  1283.                         $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  1284.     
  1285.                     }
  1286.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  1287.                 }
  1288.             }    
  1289.             
  1290.             if ($clientes == 7) {
  1291.                   
  1292.                   $pdf->setVencimentoDocumento(new \DateTimeImmutable($fase));
  1293.                   $pdf->setDataDocumento(new \DateTimeImmutable($data));
  1294.              }
  1295.              
  1296.             $pdf->setAssunto($assunto);
  1297.             if ($classifica != "") {
  1298.                 $classifica_id = $doctrine->getRepository(Classificacao::class)->find($classifica);
  1299.                 $pdf->setClassificacao($classifica_id);
  1300.             }
  1301.             $pdf->setExtraFields($desc);
  1302.             $pdf->setNome($nome);
  1303.             $pdf->setKeywords($chave);
  1304.             $pdf->setUserIndex($user_nome_name);
  1305.             $pdf->setConteiner($conteiner);
  1306.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  1307.             $pdf->setTipo($index_tipo);
  1308.             $entityManager->flush();
  1309.             $id_pd = $pdf->getId();    
  1310.             $log = new Registro();
  1311.             $log->setOperacao('Indexou o Documento com id '.$id_pd); 
  1312.             $log->setUser($user_nome_name);
  1313.             $log->setCliente($cliente_nome);
  1314.             $entityManager->persist($log);
  1315.             $entityManager->flush();
  1316.             $erro = 'ok';
  1317.             $p =  $index_tipo_tipo.' indexado com sucesso';
  1318.             
  1319.            
  1320.             
  1321.            
  1322.         }   
  1323.         if(isset($_POST["botao_index_edit"])){
  1324.             
  1325.             $yz = 0 ;
  1326.             $xy = 1 ;
  1327.             $ay = 1 ;
  1328.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  1329.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  1330.             $link = $pdf->getImage();
  1331.         }
  1332.         if(isset($_POST["botao_volta"])){
  1333.             $xy = 0 ;
  1334.             $yz = 0 ;
  1335.         }
  1336.         if(isset($_POST["index_button"])){
  1337.             
  1338.             
  1339.             $yz = 0 ;
  1340.             $xy = 1 ;
  1341.             $ay = 1 ;
  1342.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  1343.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["index_button"]);
  1344.             $link = $pdf->getImage();
  1345.         }
  1346.         if(isset($_POST["botao_cancel"])){
  1347.             $yz = 0 ;
  1348.             $xy = 1 ;
  1349.             $ay = 0 ;
  1350.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  1351.             $link = $pdf->getImage();
  1352.             
  1353.         }
  1354.         if(isset($_POST["delet"])){
  1355.            
  1356.             $ky = 1 ;
  1357.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["delet"]);
  1358.             $documentos = $doctrine->getRepository(Documento::class)->findBy(['id' => $_POST["delet"]]);
  1359.             
  1360.             if($pdf->getTipo()!= null){
  1361.                 $index_find =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  1362.                 $pagina =$index_find->getTipo();
  1363.                 $pagina_h4 ='Documento(s) do tipo ( '.$index_find->getTipo().' )';
  1364.             }
  1365.                         
  1366.         }
  1367.         if(isset($_POST["delet_cancel"])){
  1368.             $ky = 0 ;
  1369.         }
  1370.         if(isset($_POST["delet_sim"])){
  1371.             
  1372.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  1373.             $id_pd = $pdf->getId();
  1374.             $entityManager->remove($pdf);
  1375.             $entityManager->flush();
  1376.           
  1377.             $log = new Registro();
  1378.             $log->setOperacao('Excluiu Documento com id '.$id_pd); 
  1379.             $log->setUser($user_nome_name);
  1380.             $log->setCliente($cliente_nome);
  1381.             $entityManager->persist($log);
  1382.             $entityManager->flush();
  1383.             $erro = 'ok';
  1384.             $p = 'Documento com id '.$id_pd.' excluido com sucesso '; 
  1385.         }
  1386.         if(isset($_POST["index_edit"])){
  1387.             $yz = 0 ;
  1388.             $xy = 1 ;
  1389.             $ay = 2 ;
  1390.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  1391.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  1392.             $link = $pdf->getImage();
  1393.         }
  1394.        
  1395.        
  1396.         $cmd = $clientS3->getCommand('GetObject', [
  1397.                 'Bucket' => 'arquivosdoc',
  1398.                 'Key'    => $caminho. $link, 
  1399.             ]);
  1400.             
  1401.             $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  1402.             $all_Url = (string) $req->getUri();
  1403.         return $this->render('index/index1.html.twig', [
  1404.             'documentos' => $documentos,
  1405.             'xy' => $xy,
  1406.             'yz' => $yz,
  1407.             'ay'=>$ay,
  1408.             'link' => $link,
  1409.             'pdf'=>$pdf,
  1410.             'p'=>$p,
  1411.             'erro'=>$erro,
  1412.             'index_all'=>$index_all,
  1413.             'index_tipo'=>$index_tipo,
  1414.             'ky'=>$ky,
  1415.             'pagina' => $pagina,
  1416.             'pagina_h4' =>$pagina_h4,
  1417.             'index_find'=>$index_find,
  1418.             'mx'=>$mx,
  1419.             'caixas' => $caixas,
  1420.             'class' => $class,
  1421.             'permissao'=>$permissao,
  1422.             'caminho' =>$caminho,
  1423.             'clientes' => $clientes,
  1424.             'doc'=>$doc,
  1425.             'dia_prod' => $dia_prod,
  1426.             'cliente_session' => $cliente_session,
  1427.             'all_Url'=>$all_Url
  1428.         ]);
  1429.     }
  1430.     
  1431.     #[Route('/index/novo/fluxo', name: 'fluxo_novo')]
  1432.     public function fluxoNovo(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer): Response
  1433.     {
  1434.         $user_logado = $this->getUser();
  1435.         $user_logado_nome = $user_logado->getNome();
  1436.         $user_logado_id = $user_logado->getId();
  1437.         $erro = '';
  1438.         $pagina = 'fluxo';
  1439.         $p ='';
  1440.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  1441.         
  1442.         if(isset($_POST["btn_cliente"])){
  1443.             
  1444.             $session->set('cliente_id', $_POST["btn_cliente"]);
  1445.             return $this->redirectToRoute('home');
  1446.         }
  1447.         $clienteId = $session->get('cliente_id');
  1448.         
  1449.       
  1450.         
  1451.         if ($clienteId == null ) {
  1452.             
  1453.             $cli =  "";
  1454.             return $this->redirectToRoute('home');
  1455.           
  1456.        
  1457.         } else {
  1458.             
  1459.          
  1460.             $cli = $doctrine->getRepository(Cliente::class)->find($clienteId);
  1461.             
  1462.         }
  1463.         
  1464.         $query = $doctrine->getManager()->createQuery('
  1465.             SELECT u
  1466.             FROM App\Entity\User u
  1467.             JOIN u.clientes c
  1468.             WHERE c.id = :clientId
  1469.             AND u.enabled = 1
  1470.         ')->setParameter('clientId', $clienteId);
  1471.         $usuarios = $query->getArrayResult();
  1472.         if(isset($_POST["fluxo"])){
  1473.             
  1474.             $fluxo = new Fluxo();
  1475.             $nome = $cli->getNome();
  1476.             $fluxo->setNome($nome);
  1477.             $fluxo->setUser($user_logado);
  1478.             $fluxo->setCliente($cli);
  1479.             $fluxo->setObs($_POST["obs"]);
  1480.             $entityManager->persist($fluxo);
  1481.             $entityManager->flush();
  1482.             $id_fluxo = $fluxo->getId(); 
  1483.             
  1484.             $prazo = $_POST["prazo"];
  1485.             $user_1 = $_POST["user"];
  1486.             
  1487.             foreach ($user_1 as $users) {
  1488.                
  1489.                     $etapa = new Etapa();
  1490.                     $user = $doctrine->getRepository(User::class)->find($users);
  1491.                     $mail = $user->getEmail();
  1492.                     
  1493.                    
  1494.                     $etapa->setNome($_POST["etapa"]);
  1495.                     $etapa->setOrdem(1);
  1496.                     $etapa->setUser($user);
  1497.                     $etapa->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1498.                     $etapa->setPrazo(new \DateTimeImmutable($prazo));
  1499.                     $entityManager->persist($etapa);
  1500.                     $entityManager->flush();
  1501.         
  1502.                     /*$email = (new Email())
  1503.                         ->from('arquivosdoc@arquivosdoc.com.br')
  1504.                         ->to($mail)
  1505.                         ->subject('Fluxo de Trabalho')
  1506.                         ->html('<div style="text-align: center;">
  1507.                             <h1 style="color:#1e4067;">Recebimento<br>
  1508.                             Cliente: '.$nome.'<br>
  1509.                             Prazo:'.$prazo.'<br>
  1510.                             Enviado por: '.$user_logado_nome.'<br>
  1511.                             Acesse sua pagina inicial no <a href="https://ged.arquivosdoc.com.br/login">ArquivosGED
  1512.                             </a></h1>
  1513.                             <img src="cid:logo"><div>')
  1514.                         ->embed(fopen('C:/xampp8/htdocs/gedemail/public/img/icon.png', 'r'), 'logo', 'image/png');
  1515.                     $mailer->send($email);*/
  1516.                     
  1517.                  
  1518.             }
  1519.             
  1520.             if(isset($_POST["user_2"])){
  1521.                 
  1522.                 
  1523.                 $prazo_2 = $_POST["prazo_2"];
  1524.                 $user_2 = $_POST["user_2"];
  1525.                 foreach ($user_2 as $users2) {
  1526.                     $etapa2 = new Etapa();
  1527.                     $etapa2->setNome($_POST["etapa2"]);
  1528.                     $etapa2->setOrdem(2);
  1529.                     $etapa2->setUser($doctrine->getRepository(User::class)->find($users2));
  1530.                     $etapa2->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1531.                     $etapa2->setPrazo(new \DateTimeImmutable($prazo_2));
  1532.                     $entityManager->persist($etapa2);
  1533.                     $entityManager->flush();
  1534.                 }
  1535.             }
  1536.             if(isset($_POST["user_3"])){
  1537.                 
  1538.                 
  1539.                 $user_3 = $_POST["user_3"];
  1540.                 $prazo_3 = $_POST["prazo_3"];
  1541.                 foreach ($user_3 as $users3) {
  1542.                     $etapa3 = new Etapa();
  1543.                     $etapa3->setNome($_POST["etapa3"]);
  1544.                     $etapa3->setOrdem(3);
  1545.                     $etapa3->setUser($doctrine->getRepository(User::class)->find($users3));
  1546.                     $etapa3->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1547.                     $etapa3->setPrazo(new \DateTimeImmutable($prazo_3));
  1548.                     $entityManager->persist($etapa3);
  1549.                     $entityManager->flush();
  1550.                 }    
  1551.             }
  1552.             if(isset($_POST["user_4"])){
  1553.                 
  1554.                 $user_4 = $_POST["user_4"];
  1555.                 $prazo_4 = $_POST["prazo_4"];
  1556.                 foreach ($user_4 as $users4) {
  1557.                     $etapa4 = new Etapa();
  1558.                     $etapa4->setNome($_POST["etapa4"]);
  1559.                     $etapa4->setOrdem(4);
  1560.                     $etapa4->setUser($doctrine->getRepository(User::class)->find($users4));
  1561.                     $etapa4->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1562.                     $etapa4->setPrazo(new \DateTimeImmutable($prazo_4));
  1563.                     $entityManager->persist($etapa4);
  1564.                     $entityManager->flush();
  1565.                 }
  1566.             } 
  1567.             
  1568.             
  1569.             if(isset($_POST["user_5"])){
  1570.                 
  1571.                 $user_5 = $_POST["user_5"];
  1572.                 $prazo_5 = $_POST["prazo_5"];
  1573.                 foreach ($user_5 as $users5) {
  1574.                     $etapa5 = new Etapa();
  1575.                     $etapa5->setNome($_POST["etapa5"]);
  1576.                     $etapa5->setOrdem(5);
  1577.                     $etapa5->setUser($doctrine->getRepository(User::class)->find($users5));
  1578.                     $etapa5->setFluxo($doctrine->getRepository(Fluxo::class)->find($id_fluxo));
  1579.                     $etapa5->setPrazo(new \DateTimeImmutable($prazo_5));
  1580.                     $entityManager->persist($etapa5);
  1581.                     $entityManager->flush();
  1582.                 }
  1583.             } 
  1584.             $erro = "ok";
  1585.             $p =  'FLUXO ENVIADO' ;
  1586.             
  1587.             
  1588.         }
  1589.         
  1590.     
  1591.        
  1592.         return $this->render('index/index4.html.twig', [
  1593.     
  1594.             
  1595.             'p'=>$p,
  1596.             'erro'=>$erro,
  1597.             'pagina' => $pagina,
  1598.             'usuarios' =>$usuarios,
  1599.             'cliente' => $cliente
  1600.             
  1601.         ]);
  1602.     }
  1603.     #[Route('/index/fluxo', name: 'fluxo')]
  1604.     public function fluxo( PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer): Response
  1605.     {
  1606.         $user_logado = $this->getUser();
  1607.         $erro = '';
  1608.         $pagina = 'fluxo';
  1609.         $p ='';
  1610.         #$registro = $doctrine->getRepository(Registro::class)->findAll();
  1611.         $a = 0;
  1612.         $clientS3 = new  S3Client([
  1613.             'region'  => 'sa-east-1',
  1614.             'version' => 'latest',
  1615.             'credentials' => [ 
  1616.                 'key'    => $_ENV['AWS_KEY'],
  1617.                 'secret' => $_ENV['AWS_SECRET'],
  1618.             ],
  1619.         
  1620.         ]);
  1621.         
  1622.     
  1623.         if(isset($_POST["btn_cliente"])){
  1624.             
  1625.             $session->set('cliente_id', $_POST["btn_cliente"]);
  1626.             return $this->redirectToRoute('home');
  1627.         }
  1628.         $clienteId = $session->get('cliente_id');
  1629.         
  1630.         if($clienteId == null){
  1631.             
  1632.             return $this->redirectToRoute('home');
  1633.         }
  1634.         
  1635.         $cliente = $doctrine->getRepository(Cliente::class)->find($clienteId);
  1636.         $fluxo = $doctrine->getRepository(Fluxo::class)->findBy(['cliente' => $clienteId],['id'=> 'DESC']);
  1637.       
  1638.         
  1639.         // Paginar os fluxos
  1640.         $fluxos = $paginator->paginate(
  1641.             $fluxo, // O queryBuilder ou a query
  1642.             $request->query->getInt('page', 1), // A página atual, padrão é 1
  1643.             2 // O número de itens por página
  1644.         );
  1645.         if (isset($_POST["excel"])) {
  1646.             
  1647.         
  1648.             $cx = null;
  1649.             $id_fluxo = $_POST["excel"];
  1650.             $fluxo_excel = $doctrine->getRepository(Fluxo::class)->find($id_fluxo);
  1651.             $nome_fluxo = $fluxo_excel->getNome();
  1652.             $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_excel->getId());
  1653.             
  1654.             
  1655.         
  1656.             // Cria uma nova planilha
  1657.             $spreadsheet = new Spreadsheet();
  1658.             $sheet = $spreadsheet->getActiveSheet();
  1659.             $sheet->setTitle('CAIXA(S)');
  1660.             // Configura o cabeçalho
  1661.             $sheet->setCellValue('A1', 'ID');
  1662.             $sheet->setCellValue('B1', 'REPOSITOR');
  1663.             $sheet->setCellValue('C1', 'DATA DO ENVIO');
  1664.         
  1665.             // Estiliza o cabeçalho (fundo azul, texto branco e negrito)
  1666.             $headerStyle = [
  1667.                 'font' => [
  1668.                     'bold' => true,
  1669.                     'color' => ['rgb' => 'FFFFFF'], // Texto branco
  1670.                 ],
  1671.                 'fill' => [
  1672.                     'fillType' => Fill::FILL_SOLID,
  1673.                     'startColor' => ['rgb' => '095f99'], // Fundo azul
  1674.                 ],
  1675.             ];
  1676.             $sheet->getStyle('A1:C1')->applyFromArray($headerStyle);
  1677.         
  1678.             // Preenche os dados
  1679.             $rowCount = 2;
  1680.             foreach ($fluxo_caixas as $caixas) {
  1681.                 
  1682.                     if($caixas->getCx() != null){
  1683.                     
  1684.                     $nome = $caixas->getNome();
  1685.                     $cx = $caixas->getCx()->getNome();
  1686.                     $data = $caixas->getCreatedAt();
  1687.             
  1688.                     // Insere os valores
  1689.                     $sheet->setCellValue('A' . $rowCount, $cx);
  1690.                     $sheet->setCellValue('B' . $rowCount, $nome);
  1691.             
  1692.                     // Converte a data para o formato Excel
  1693.                     if ($data instanceof \DateTime) {
  1694.                         $sheet->setCellValue('C' . $rowCount, Date::PHPToExcel($data));
  1695.                     } else {
  1696.                         $sheet->setCellValue('C' . $rowCount, $data); // Evita erro se não for DateTime
  1697.                     }
  1698.             
  1699.                     $rowCount++;
  1700.                 }
  1701.             }
  1702.         
  1703.             // Formata a coluna C como data (exceto o cabeçalho)
  1704.             $sheet->getStyle('C2:C' . ($rowCount - 1))
  1705.                 ->getNumberFormat()
  1706.                 ->setFormatCode('dd/mm/yyyy');
  1707.         
  1708.             // Define largura automática das colunas
  1709.             foreach (range('A', 'C') as $col) {
  1710.                 $sheet->getColumnDimension($col)->setAutoSize(true);
  1711.             }
  1712.              // Segunda aba - Outras informações (Exemplo)
  1713.             $sheet2 = $spreadsheet->createSheet(); // Cria uma nova aba
  1714.             $sheet2->setTitle('DOCUMENTO(S)'); // Renomeia a aba
  1715.             $sheet2->setCellValue('A1' , 'ID');
  1716.             $sheet2->setCellValue('B1' , 'NOME');
  1717.             $sheet2->setCellValue('C1' , 'REPOSITOR');
  1718.             $sheet2->setCellValue('D1' , 'TIPO');
  1719.             $sheet2->setCellValue('E1' , 'ASSUNTO');
  1720.             $sheet2->setCellValue('F1' , 'PALAVRA-CHAVE');
  1721.             $sheet2->setCellValue('G1' , 'DIGITALIZAÇÃO');
  1722.             $sheet2->setCellValue('H1' , 'QUEM DIGITALIZOU?');
  1723.             $sheet2->setCellValue('I1' , 'INDEXAÇÃO');
  1724.             $sheet2->setCellValue('J1' , 'QUEM INDEXOU?');
  1725.             $sheet2->setCellValue('K1' , 'IMAGEN(S)');
  1726.             $sheet2->getStyle('A1:K1')->applyFromArray($headerStyle);
  1727.             
  1728.             $rowCount = 2;
  1729.             foreach ($fluxo_caixas as $caixas) {
  1730.                 $doc = $caixas->getDocumentos();
  1731.                 
  1732.                 foreach ($doc as $docs) {
  1733.                     $tipo= null;
  1734.                     $id = $docs->getId();
  1735.                     $nome = $docs->getNome();
  1736.                     $caixa = $docs->getCaixa()->getNome();
  1737.                     if($docs->getTipo() != null){
  1738.                         $tipo = $docs->getTipo()->getNome();
  1739.                     }
  1740.                     $qtd = $docs->getQtd();
  1741.                     $assunto = $docs->getAssunto();
  1742.                     $keywords = $docs->getKeywords();
  1743.                     $user = $docs->getUser()->getNome();
  1744.                     $data  = $docs->getCreatedAt();
  1745.                     $index  = $docs->getIndexAt();
  1746.                     $user_index  = $docs->getUserIndex();
  1747.                     $sheet2->setCellValue('A' . $rowCount,$id);
  1748.                     $sheet2->setCellValue('B' . $rowCount,$nome);
  1749.                     $sheet2->setCellValue('C' . $rowCount,$caixa);
  1750.                     $sheet2->setCellValue('D' . $rowCount,$tipo);
  1751.                     $sheet2->setCellValue('E' . $rowCount,$assunto);
  1752.                     $sheet2->setCellValue('F' . $rowCount,$keywords);
  1753.                     $sheet2->setCellValue('G' . $rowCount,$data);
  1754.                     $sheet2->setCellValue('H' . $rowCount,$user);
  1755.                     $sheet2->setCellValue('I' . $rowCount,$index);
  1756.                     $sheet2->setCellValue('J' . $rowCount,$user_index);
  1757.                     $sheet2->setCellValue('K' . $rowCount,$qtd);
  1758.                    
  1759.                     
  1760.                     if ($data instanceof \DateTime) {
  1761.                         $sheet2->setCellValue('G' . $rowCount, Date::PHPToExcel($data));
  1762.                     } else {
  1763.                         $sheet2->setCellValue('G' . $rowCount, $data); // Evita erro se não for DateTime
  1764.                     }
  1765.                     if ($data instanceof \DateTime) {
  1766.                         $sheet2->setCellValue('I' . $rowCount, Date::PHPToExcel($index));
  1767.                     } else {
  1768.                         $sheet2->setCellValue('I' . $rowCount, $index); // Evita erro se não for DateTime
  1769.                     }
  1770.             
  1771.             
  1772.                     $rowCount++;
  1773.                 
  1774.                 }
  1775.             }
  1776.             $sheet2->getStyle('I2:I' . ($rowCount - 1))
  1777.                 ->getNumberFormat()
  1778.                 ->setFormatCode('dd/mm/yyyy');
  1779.             $sheet2->getStyle('G2:G' . ($rowCount - 1))
  1780.                 ->getNumberFormat()
  1781.                 ->setFormatCode('dd/mm/yyyy');    
  1782.         
  1783.             foreach (range('A', 'K') as $col) {
  1784.                 $sheet2->getColumnDimension($col)->setAutoSize(true);
  1785.             }
  1786.         
  1787.             // Gera o arquivo para download
  1788.             $writer = new Xlsx($spreadsheet);
  1789.             header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  1790.             header('Content-Disposition: attachment; filename="' . $nome_fluxo . '-FLUXO-' . $id_fluxo . '.xlsx"');
  1791.             header('Cache-Control: max-age=0');
  1792.             $writer->save('php://output');
  1793.             exit;
  1794.         }
  1795.         if (isset($_POST["pdf"])) {
  1796.             
  1797.             $id_fluxo = $_POST["pdf"];
  1798.             $fluxo_pdf = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  1799.             $nome_fluxo = $fluxo_pdf->getNome();
  1800.             
  1801.            
  1802.             $html = $this->render('index/pdf.html.twig', [
  1803.                 'fluxo_pdf' => $fluxo_pdf,
  1804.                 'registro' => $registro
  1805.                 
  1806.             ]);
  1807.             $options = new Options();
  1808.             $options->set('isHtml5ParserEnabled', true);
  1809.             $options->set('isPhpEnabled', true);
  1810.             $options->set('isRemoteEnabled', true); 
  1811.             $dompdf = new Dompdf($options);
  1812.             $dompdf->loadHtml($html);
  1813.             $dompdf->setPaper('A4', 'portrait');
  1814.             // Renderiza o HTML para o PDF
  1815.             $dompdf->render();
  1816.             // Envia o PDF para o navegador para download
  1817.             $dompdf->stream("Relatório_Fluxo_".$id_fluxo."_".$nome_fluxo.".pdf", ["Attachment" => 0]); // 0 para exibir no navegador, 1 para download
  1818.         }
  1819.         if (isset($_POST["etiqueta"])) {
  1820.             try {
  1821.         
  1822.                 // reforça limites (pode ajustar conforme necessário)
  1823.                 ini_set('max_execution_time', 500);
  1824.                 ini_set('memory_limit', '3512M');
  1825.         
  1826.                 $id_fluxo = $_POST["etiqueta"];
  1827.                 $fluxo_pdf = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  1828.                 $cliente_id = $fluxo_pdf->getCliente()->getId();
  1829.                 $cliente = $doctrine->getRepository(Cliente::class)->findWithRelations($cliente_id);
  1830.                 $nome_fluxo = $fluxo_pdf->getNome();
  1831.                 $clienteAll_fluxo = $cliente->getClienteAll()->getLogo();
  1832.                 
  1833.                 $cmd = $clientS3->getCommand('GetObject', [
  1834.                 'Bucket' => 'arquivosdoc',
  1835.                 'Key'    => 'LOGO_CLIENTES/'. $clienteAll_fluxo, 
  1836.                 ]);
  1837.                 
  1838.                 $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  1839.                 $cliente_all_Url = (string) $req->getUri();
  1840.                 
  1841.                 $clienteAll_fluxo_id = $cliente->getClienteAll()->getId();
  1842.                 $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_pdf->getId());
  1843.                 if ($cliente_id == 139 or $cliente_id == 137){
  1844.                         $html = '
  1845.                         <!DOCTYPE html>
  1846.                         <html lang="pt-BR">
  1847.                         <head>
  1848.                             <meta charset="UTF-8">
  1849.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  1850.                             <title>FLUXO</title>
  1851.                             <style>
  1852.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  1853.                                 body { text-transform: uppercase; }
  1854.                                 .filho { border: 2px solid black; width: 57.2mm; height: 100mm; display: inline-block; margin: 2px; position: relative;}
  1855.                                 h2 { text-align: center; font-size: 20px; padding: 5px; }
  1856.                                 h2 img{width: 250px; height: 250px;}
  1857.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  1858.                                 h5 { text-align: center; font-size: 14px;}
  1859.                                 h6 { text-align: center; font-size: 14px; padding: 5px; }
  1860.                                 h5 img { text-align: center;max-height: 40px;width:auto;max-width: 40px}
  1861.                                 h6 img { text-align: center;margin:auto;  max-height: 130px;width:auto;max-width: 130px}
  1862.                                 p { text-align: center; font-size: 8px; font-weight: bold;}
  1863.                                 .pai { position: relative; top: 11%; }
  1864.                                 hr { color: black; }
  1865.                                 .lis2{
  1866.                                     
  1867.                                     font-weight: bold;
  1868.                                     margin:5px;
  1869.                                 }
  1870.                                 .lis3 {
  1871.                                     position: absolute;
  1872.                                     bottom: 0;
  1873.                                     width: 100%;
  1874.                                     font-weight: bold;
  1875.                                     text-align: center;
  1876.                                     margin-bottom:5px;
  1877.                                     margin-top:5px;
  1878.                                        
  1879.                                 }
  1880.                                 .lis{
  1881.                                     
  1882.                                     margin-left:10px;
  1883.                                     font-weight: bold;
  1884.                                 }
  1885.                                 li{
  1886.                                   margin:5px;
  1887.                                   font-size: 12px
  1888.                                 }
  1889.                                 
  1890.                             </style>
  1891.                         </head>
  1892.                         <body>
  1893.                         <div class="pai">';
  1894.                 
  1895.                         $count = 0;
  1896.                 
  1897.                         foreach ($fluxo_caixas as $caixa) {
  1898.                             $count++;
  1899.                             $documento_fluxo = $caixa->getDocumentos()->toArray();
  1900.                             
  1901.                 
  1902.                             $html .= '<div class="filho">
  1903.                                 
  1904.                                 
  1905.                                 <h6><img src="'.$cliente_all_Url.'" class="img"></h6>
  1906.                                 <hr>
  1907.                                 <h2>' . htmlspecialchars($caixa->getNome()) . '</h2>
  1908.                                 <hr>
  1909.                                 ';
  1910.                 
  1911.                             $docs = [];
  1912.                             
  1913.                             if (!empty($documento_fluxo)) {
  1914.                                 foreach ($documento_fluxo as $doc) {
  1915.                                     if($doc->getTipo() != NULL ){
  1916.                                         if ($cliente_id != 122) {
  1917.                                             $docs[] = $doc->getTipo()->getNome();
  1918.                                         } else {
  1919.                                             $docs[] = $doc->getNome();
  1920.                                         }
  1921.                                     }
  1922.                                 }
  1923.                                 $docs = array_unique($docs);
  1924.                             }
  1925.                             
  1926.                             
  1927.                             $docs_class = [];
  1928.                             
  1929.                             if (!empty($documento_fluxo)) {
  1930.                                 foreach ($documento_fluxo as $doc) {
  1931.                                     
  1932.                                     if($doc->getClassificacao() != NULL ){
  1933.                                        $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  1934.                                        $class_nome =  $clss[0]->getNome();
  1935.                                        $docs_class[] = $class_nome;
  1936.                                         
  1937.                                     }
  1938.                                 }
  1939.                                 $docs_class = array_unique($docs_class);
  1940.                             }
  1941.                 
  1942.                             $docs_data = [];
  1943.                             $docs_assunto=[];
  1944.                             if (!empty($documento_fluxo)) {
  1945.                                 foreach ($documento_fluxo as $data) {
  1946.                                     if ($data->getNome() !== null) {
  1947.                                         $docs_data[] = $data->getNome();
  1948.                                     }
  1949.                                     if ($data->getAssunto() !== null) {
  1950.                                         $docs_assunto[] = $data->getAssunto();
  1951.                                     }
  1952.                                 }
  1953.                                 $docs_data = array_unique($docs_data);
  1954.                                 $docs_assunto = array_unique($docs_assunto);
  1955.                             }
  1956.                             
  1957.                              if ($cliente_id == 139){
  1958.                        
  1959.                                 $pl_numeros = [];
  1960.                                 $req_numeros = [];
  1961.                                 $req_ano = null;
  1962.                                 
  1963.                                 foreach ($docs_data as $doc) {
  1964.                                 
  1965.                                 
  1966.                                     if (preg_match('/^PL-(\d{1,3}(?:\.\d{3})*)$/', $doc, $m)) {
  1967.                                 
  1968.                                         $numeroLimpo = str_replace('.', '', $m[1]);
  1969.                                         $pl_numeros[] = (int)$numeroLimpo;
  1970.                                     }
  1971.                                 
  1972.                            
  1973.                                     elseif (stripos($doc, 'REQUERIMENTO') !== false 
  1974.                                         && preg_match('/-(\d+)\.(\d{4})$/', $doc, $m)) {
  1975.                                 
  1976.                                         $req_numeros[] = (int)$m[1];
  1977.                                         $req_ano = $m[2];
  1978.                                     }
  1979.                                 }
  1980.                                 
  1981.                         
  1982.                                 
  1983.                                 $menorNome = null;
  1984.                                 $maiorNome = null;
  1985.                                 $docs_faltantes = [];
  1986.                                 $tipoAtual = null;
  1987.                                 
  1988.                           
  1989.                                 
  1990.                                 if (!empty($pl_numeros)) {
  1991.                                 
  1992.                                     sort($pl_numeros);
  1993.                                 
  1994.                                     $menor = min($pl_numeros);
  1995.                                     $maior = max($pl_numeros);
  1996.                                 
  1997.                                     $menorNome = 'PL ' . number_format($menor, 0, '', '.');
  1998.                                     $maiorNome = 'PL ' . number_format($maior, 0, '', '.');
  1999.                                 
  2000.                                     $esperado = range($menor, $maior);
  2001.                                     $faltantes = array_diff($esperado, $pl_numeros);
  2002.                                 
  2003.                                     foreach ($faltantes as $f) {
  2004.                                         $docs_faltantes[] = 'PL ' . number_format($f, 0, '', '.');
  2005.                                     }
  2006.                                 
  2007.                                     $tipoAtual = 'PL';
  2008.                                 }
  2009.                                 
  2010.                           
  2011.                                 
  2012.                                 elseif (!empty($req_numeros)) {
  2013.                                 
  2014.                                     sort($req_numeros);
  2015.                                 
  2016.                                     $menor = min($req_numeros);
  2017.                                     $maior = max($req_numeros);
  2018.                                 
  2019.                                     $menorNome = str_pad($menor, 2, '0', STR_PAD_LEFT) . '.' . $req_ano;
  2020.                                     $maiorNome = str_pad($maior, 2, '0', STR_PAD_LEFT) . '.' . $req_ano;
  2021.                                 
  2022.                                     $esperado = range($menor, $maior);
  2023.                                     $faltantes = array_diff($esperado, $req_numeros);
  2024.                                 
  2025.                                     foreach ($faltantes as $f) {
  2026.                                         $docs_faltantes[] = str_pad($f, 2, '0', STR_PAD_LEFT) . '.' . $req_ano;
  2027.                                     }
  2028.                                 
  2029.                                     $tipoAtual = 'REQUERIMENTO';
  2030.                                 }                                                                        
  2031.                                                                                                                             
  2032.                                                                 
  2033.                                     $html .= '<h6>' . htmlspecialchars(implode(', ', $docs)) . '</h6>
  2034.                                     <hr>';
  2035.                                    
  2036.     
  2037.     
  2038.                                     $html .= '<h6>Conteúdo:</h6>';
  2039.     
  2040.                                     $html .= '<div class="lis">';
  2041.                                     foreach ($docs_class as $classs_nome) {
  2042.                                     $html .= '
  2043.                                         <li>' . $classs_nome. '</li>';
  2044.                                     }
  2045.                                     $html .= '</div><br>';
  2046.                                     
  2047.                                     
  2048.                                     if ($menorNome !== null && $maiorNome !== null) {
  2049.                                         $html .= '<h6>'.$menorNome.' Até '.$maiorNome.'</h6>';
  2050.                                     }
  2051.         
  2052.                                     if($docs_faltantes != []){
  2053.                                         $html .= '
  2054.                                         <div class="lis2"><p>';
  2055.                                                 $html .= 'Faltantes*</br>';
  2056.                                                 $qtdFaltantes = count($docs_faltantes);
  2057.     
  2058.                                                 if ($qtdFaltantes > 40) {
  2059.                                                 
  2060.                                                     $html .= '<span style="color:red; font-weight:bold;font-size: 8px">
  2061.                                                         Existem ' . $qtdFaltantes . ($tipoAtual === 'PL' ? ' projetos de lei ' : ' requerimentos ') . 'faltantes.
  2062.                                                         Conferir no inventário.
  2063.                                                     </span>';
  2064.                                                 
  2065.                                                 } else {
  2066.                                                 
  2067.                                                 $html .= implode(' | ', $docs_faltantes);
  2068.     
  2069.                                                 
  2070.                                                 }
  2071.                                             
  2072.                                         $html .= '</p></div>';
  2073.                                     }
  2074.                                 }
  2075.                                 else{
  2076.                                     
  2077.                                                                 // Remove duplicados
  2078.                                 $docs_assunto = array_unique($docs_assunto);
  2079.                                 
  2080.                                 // Converte para DateTime
  2081.                                 $datasObj = array_map(function ($data) {
  2082.                                     return DateTime::createFromFormat('m/Y', $data);
  2083.                                 }, $docs_assunto);
  2084.                                 
  2085.                                 // Remove possíveis datas inválidas
  2086.                                 $datasObj = array_filter($datasObj);
  2087.                                 
  2088.                                 // Ordena por data
  2089.                                 usort($datasObj, function ($a, $b) {
  2090.                                     return $a <=> $b;
  2091.                                 });
  2092.                                 
  2093.                                 $resultado = [];
  2094.                                 
  2095.                                 if (count($datasObj) > 0) {
  2096.                                 
  2097.                                     $inicio = $datasObj[0];
  2098.                                     $anterior = $datasObj[0];
  2099.                                 
  2100.                                     for ($i = 1; $i < count($datasObj); $i++) {
  2101.                                 
  2102.                                         $atual = $datasObj[$i];
  2103.                                 
  2104.                                         $proximoEsperado = clone $anterior;
  2105.                                         $proximoEsperado->modify('+1 month');
  2106.                                 
  2107.                                         if ($atual->format('m/Y') !== $proximoEsperado->format('m/Y')) {
  2108.                                 
  2109.                                             if ($inicio->format('m/Y') === $anterior->format('m/Y')) {
  2110.                                                 $resultado[] = $inicio->format('m/Y');
  2111.                                             } else {
  2112.                                                 $resultado[] = $inicio->format('m/Y') . ' até ' . $anterior->format('m/Y');
  2113.                                             }
  2114.                                 
  2115.                                             $inicio = $atual;
  2116.                                         }
  2117.                                 
  2118.                                         $anterior = $atual;
  2119.                                     }
  2120.                                 
  2121.                                     // Fecha o último bloco
  2122.                                     if ($inicio->format('m/Y') === $anterior->format('m/Y')) {
  2123.                                         $resultado[] = $inicio->format('m/Y');
  2124.                                     } else {
  2125.                                         $resultado[] = $inicio->format('m/Y') . ' Até ' . $anterior->format('m/Y');
  2126.                                     }
  2127.                                 }
  2128.                                 
  2129.                                     
  2130.                                     
  2131.                                     
  2132.                                     
  2133.                                     $html .= '<h6>Conteúdo:</h6>';
  2134.     
  2135.                                     $html .= '<div class="lis">';
  2136.                                     foreach ($docs_class as $classs_nome) {
  2137.                                     $html .= '
  2138.                                         <li>' . $classs_nome. '</li>';
  2139.                                     }
  2140.                                     $len = count($resultado);
  2141.                                     if ($len <5 and $len >0) {
  2142.                                          
  2143.                                          $html .= '<br>';     
  2144.                                     }
  2145.                                     foreach ($docs_data as $classs_nome) {
  2146.                                     $html .= '
  2147.                                         <h6>' . $classs_nome. '</h6>';
  2148.                                     }
  2149.                                     
  2150.                                     
  2151.                                     
  2152.                                         
  2153.                                     foreach ($resultado as $classs_nome) {
  2154.                                         if ($len >= 9) {
  2155.                                             $fontSize = 8;
  2156.                                         } 
  2157.                                         elseif ($len <10 and $len >5) {
  2158.                                             $fontSize = 10;
  2159.                                         }
  2160.                                         
  2161.                                         elseif ($len <5 and $len >0) {
  2162.                                             $fontSize = 12;
  2163.                                              
  2164.                                         }else{
  2165.                                             $fontSize = 8;
  2166.                                         }
  2167.                                         
  2168.                                     $html .= '
  2169.                                         <p style="font-size: ' . $fontSize . 'px;">' . $classs_nome. '</p>';
  2170.                                     }
  2171.                                     
  2172.                                     $html .= '</div><br>';
  2173.                                 }
  2174.                                 $html .= 
  2175.                                 
  2176.                                 
  2177.                                 '<div class="lis3"><hr>
  2178.                                 
  2179.                                 <p>ARQUIVOS GESTÃO DOCUMENTAL</p>
  2180.                                 <h5><img src="https://index.arquivosdoc.com.br/img/logo_menu.png" class="img"></h5>
  2181.                                 </div>
  2182.                                 
  2183.                             </div>';
  2184.                 
  2185.                             if ($count %  10 == 0) {
  2186.                                 $html .= '<div style="page-break-after: always;"></div>';
  2187.                             }
  2188.                         }
  2189.                
  2190.                         $html .= '</div></body></html>';
  2191.                 }
  2192.         
  2193.                 if($clienteAll_fluxo_id != 17 and $clienteAll_fluxo_id != 40 and $cliente_id != 139 and $cliente_id != 137){
  2194.                         // Construção do HTML com os QR Codes
  2195.                         $html = '
  2196.                         <!DOCTYPE html>
  2197.                         <html lang="pt-BR">
  2198.                         <head>
  2199.                             <meta charset="UTF-8">
  2200.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2201.                             <title>FLUXO</title>
  2202.                             <style>
  2203.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  2204.                                 body { text-transform: uppercase; }
  2205.                                 .filho { border: 2px solid black; width: 120mm; height: 170mm; display: inline-block; margin-left: 45px; }
  2206.                                 h2 { text-align: center; font-size: 36px; padding: 5px; }
  2207.                                 h2 img{width: 200px; height: 200px;}
  2208.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  2209.                                 h5 { text-align: center; font-size: 22px; padding: 10px; }
  2210.                                 h6 { text-align: justify; font-size: 26px; padding: 5px; }
  2211.                                 h6 img { float: right;  max-height: 70px;width:auto;max-width: 170px}
  2212.                                 p { text-align: justify; font-size: 14px; font-weight: bold; padding: 10px; }
  2213.                                 .pai { position: relative; top: 20%; }
  2214.                                 hr { color: black; }
  2215.                                 .lis{
  2216.                                 
  2217.                                  width:430px; height: 200px;
  2218.                                  margin:auto;
  2219.                                  font-weight: bold;
  2220.                                 }
  2221.                                 li{
  2222.                                   margin-left:10px;
  2223.                                 }
  2224.                                 
  2225.                             </style>
  2226.                         </head>
  2227.                         <body>
  2228.                         <div class="pai">';
  2229.         
  2230.                         $count = 0;
  2231.         
  2232.                         foreach ($fluxo_caixas as $caixa) {
  2233.                             $count++;
  2234.                             $documento_fluxo = $caixa->getDocumentos()->toArray();
  2235.         
  2236.                             // Gerar QR Code
  2237.                             $qrCode = Builder::create()
  2238.                                 ->writer(new PngWriter())
  2239.                                 ->data("https://ged.arquivosdoc.com.br/info/caixa/" . $caixa->getId())
  2240.                                 ->build();
  2241.                             $qrCodeBase64 = base64_encode($qrCode->getString());
  2242.         
  2243.                             $html .= '<div class="filho">
  2244.                                 <h2>' . htmlspecialchars($caixa->getNome()) . '</h2>
  2245.                                 <hr>
  2246.                                 <h6>Arquivos:<img src="'.$cliente_all_Url.'" class="img"></h6>
  2247.                                 <p>' . htmlspecialchars($fluxo_pdf->getNome()) . '</p>
  2248.                                 <hr>
  2249.                                 <h6>Título:</h6>';
  2250.         
  2251.                             $docs = [];
  2252.                             
  2253.                             if (!empty($documento_fluxo)) {
  2254.                                 foreach ($documento_fluxo as $doc) {
  2255.                                     if($doc->getTipo() != NULL ){
  2256.                                         if ($cliente_id != 122) {
  2257.                                             $docs[] = $doc->getTipo()->getNome();
  2258.                                         } else {
  2259.                                             $docs[] = $doc->getNome();
  2260.                                         }
  2261.                                     }
  2262.                                 }
  2263.                                 $docs = array_unique($docs);
  2264.                             }
  2265.                             
  2266.                             $docs_class = [];
  2267.                             
  2268.                             if (!empty($documento_fluxo)) {
  2269.                                 foreach ($documento_fluxo as $doc) {
  2270.                                     
  2271.                                     if($doc->getClassificacao() != NULL ){
  2272.                                        $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  2273.                                        $class_nome =  $clss[0]->getNome();
  2274.                                        $docs_class[] = $class_nome;
  2275.                                        
  2276.                                         
  2277.                                     }
  2278.                                 }
  2279.                                 $docs_class = array_unique($docs_class);
  2280.                             }
  2281.                             
  2282.         
  2283.                             $html .= '<p>' . htmlspecialchars(implode(', ', $docs)) . '</p>
  2284.                                 <hr>
  2285.                                 <h6>Conteúdo:</h6>';
  2286.                                 
  2287.                                 
  2288.                                 
  2289.                                   if($clienteAll_fluxo_id == 41){
  2290.                                       
  2291.                                         $html .= '<div class="lis">';
  2292.                                         $len = count($docs_class);
  2293.                                      
  2294.                                         foreach ($docs_class as $classs_nome) {
  2295.                                         
  2296.                                         
  2297.                                             
  2298.                                             if ($len <= 9) {
  2299.                                                 $fontSize = 16;
  2300.                                             } 
  2301.                                             elseif ($len <= 11) {
  2302.                                                 $fontSize = 14;
  2303.                                             } 
  2304.                                             elseif ($len <= 13) {
  2305.                                                 $fontSize = 12;
  2306.                                             } 
  2307.                                             elseif ($len <= 16) {
  2308.                                                 $fontSize = 10;
  2309.                                             }
  2310.                                             elseif ($len <= 18) {
  2311.                                                 $fontSize = 9;
  2312.                                             }
  2313.                                             elseif ($len <= 21) {
  2314.                                                 $fontSize =8;
  2315.                                             }
  2316.                                             elseif ($len <= 23) {
  2317.                                                 $fontSize = 7;
  2318.                                             }
  2319.                                             else {
  2320.                                                 $fontSize = 6;
  2321.                                             }
  2322.                                             $html .= '<li style="font-size: ' . $fontSize . 'px;">' . $classs_nome . '</li>';
  2323.                                         }
  2324.                                         
  2325.                                         $html .= '</div>';
  2326.                                         
  2327.                                       
  2328.                                   }else{
  2329.                                              $html .= '
  2330.                                                 <h2><img src="data:image/png;base64,' . $qrCodeBase64 . '" alt="QR Code"></h2>';
  2331.                                   }  
  2332.                                         
  2333.                                 
  2334.                                 
  2335.                                 $html .= '<hr>
  2336.                                 <h4>ARQUIVOS GESTÃO DOCUMENTAL</h4>
  2337.                                 <h5><img src="https://index.arquivosdoc.com.br/img/arquivos_mini.png" class="img"></h5>
  2338.                                 <hr>
  2339.                                 <h4>Etiqueta gerada automaticamente pelo ArquivosGED</h4>
  2340.                             </div>';
  2341.         
  2342.                             if ($count % 2 == 0) {
  2343.                                 $html .= '<div style="page-break-after: always;"></div>';
  2344.                             }
  2345.                         }
  2346.                
  2347.         
  2348.                         $html .= '</div></body></html>';
  2349.                 }
  2350.         
  2351.                 
  2352.                 if($clienteAll_fluxo_id == 17 ){
  2353.                     // Construção do HTML com os QR Codes
  2354.                     $html = '
  2355.                     <!DOCTYPE html>
  2356.                     <html lang="pt-BR">
  2357.                     <head>
  2358.                         <meta charset="UTF-8">
  2359.                         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2360.                         <title>FLUXO</title>
  2361.                         <style>
  2362.                             * { margin: 0; padding: 0; font-family: Calibri, sans-serif; }
  2363.                             .filho { border: 2px solid black; width: 125mm; height: 170mm; display: inline-block; margin-left: 45px; }
  2364.                             h2 { font-size: 36px; padding: 5px; }
  2365.                             h2 img{width: 200px; height: 200px;}
  2366.                             .img_footer{width: 60px; height: 60px;position:relative;top:20px}
  2367.                             h4 { text-align: center; font-size: 12px; padding: 10px; }
  2368.                             h5 { text-align: center; font-size: 22px; padding: 10px; }
  2369.                             h6 { text-align: justify; font-size: 26px; padding: 5px; }
  2370.                             h6 img { float: right;  max-height: 77px;width:auto;max-width: 250px}
  2371.                             p { text-align: justify; font-size: 18px; font-weight: bold; padding: 10px; }
  2372.                             .pai { position: relative; top: 20%; }
  2373.                             hr { color: black; }
  2374.                             .rodape {
  2375.                                 position:relative;bottom:15px
  2376.                             }
  2377.         
  2378.                             
  2379.                         </style>
  2380.                     </head>
  2381.                     <body>
  2382.                     <div class="pai">';
  2383.             
  2384.                     $count = 0;
  2385.         
  2386.                     $codigo = "";
  2387.                     $info = "";
  2388.                     $prazo = "";
  2389.         
  2390.                     if($cliente_id == 113){
  2391.                         $codigo = "23.182";
  2392.                         $info = "PROCESSOS DIVERSOS";
  2393.                         $prazo = "57 ANOS";
  2394.                     }
  2395.         
  2396.                     if($cliente_id == 114){                        
  2397.                         $codigo = "23.11";
  2398.                         $info = "PROCESSOS DE RECURSOS HUMANOS";
  2399.                         $prazo = "100 ANOS";
  2400.                     }
  2401.             
  2402.                     foreach ($fluxo_caixas as $caixa) {
  2403.         
  2404.         
  2405.                         $texto = $caixa->getNome();
  2406.         
  2407.                         preg_match_all('/\d+/', $texto, $matches);
  2408.                         
  2409.                         if (count($matches[0]) >= 2) {
  2410.                              $numero = str_pad($matches[0][0], 3, '0', STR_PAD_LEFT); 
  2411.                             $ano = substr($texto, strpos($texto, $matches[0][0]) + strlen($matches[0][0])); 
  2412.                             $ano = trim(str_replace('-', '', $ano)); 
  2413.                         } else {
  2414.                             echo "Formato inválido!";
  2415.                         }
  2416.         
  2417.         
  2418.         
  2419.                         $count++;
  2420.                         $documento_fluxo = $caixa->getDocumentos()->toArray();
  2421.         
  2422.                         // Gerar QR Code
  2423.                         $qrCode = Builder::create()
  2424.                             ->writer(new PngWriter())
  2425.                             ->data("https://ged.arquivosdoc.com.br/info/caixa/" . $caixa->getId())
  2426.                             ->build();
  2427.                         $qrCodeBase64 = base64_encode($qrCode->getString());
  2428.             
  2429.                         $html .= '<div class="filho">
  2430.                             <h2>&nbsp;Caixa nº&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;'. htmlspecialchars($numero) . '</h2>
  2431.                             <hr>
  2432.                             <h6>ARQUIVO:<img src="'.$cliente_all_Url. '" class="img"></h6>
  2433.                             <p>SAAE VOLTA REDONDA-RJ</p>
  2434.                             <hr>
  2435.                             <h6>CÓDIGO TEMPORALIDADE:</h6>
  2436.                             <p>'.$codigo.'</p><hr>
  2437.                             <h6>TÍTULO:</h6>';
  2438.             
  2439.         
  2440.                         $html .= '<p>' . htmlspecialchars('PROCESSOS ADMINISTRATIVOS') . '</p>
  2441.                             <hr>
  2442.                             <h6>INFORMAÇÕES:</h6>
  2443.                             <p>'.$info.'</p>
  2444.                             <hr>
  2445.                             <h6>PRAZO DE GUARDA:</h6>
  2446.                             <p>'.$prazo.'</p>
  2447.                             <hr>
  2448.                             <h6>DATA:</h6>
  2449.                             <p>'.$ano.'</p>
  2450.                             <hr>
  2451.                            
  2452.                                 <p class="rodape">&nbsp;ARQUIVOS GESTÃO DOCUMENTAL&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  2453.                                 <img src="https://index.arquivosdoc.com.br/img/arquivos_mini.png" class="img_footer"></p>
  2454.                            
  2455.                             </div>';
  2456.             
  2457.                         if ($count % 2 == 0) {
  2458.                             $html .= '<div style="page-break-after: always;"></div>';
  2459.                         }
  2460.                     }
  2461.            
  2462.         
  2463.                     $html .= '</div></body></html>';
  2464.                 }
  2465.                 
  2466.                 if($clienteAll_fluxo_id == 40  ){
  2467.                         $documento_all_sebrae = $doctrine->getRepository(Documento::class)
  2468.                         ->findBy(
  2469.                             ['cliente' => $cliente_id], // filtros
  2470.                             ['id' => 'DESC'],            // ordenação (opcional)
  2471.                             100,                        // LIMIT
  2472.                             0                           // OFFSET
  2473.                         );
  2474.                         $html = '
  2475.                         <!DOCTYPE html>
  2476.                         <html lang="pt-BR">
  2477.                         <head>
  2478.                             <meta charset="UTF-8">
  2479.                             <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2480.                             <title>FLUXO</title>
  2481.                             <style>
  2482.                                 * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  2483.                                 body { text-transform: uppercase; }
  2484.                                 .filho { border: 2px solid black; width: 120mm; height: 160mm; display: inline-block; margin-left: 20px;padding:10px;} 
  2485.                                 h2 { text-align: center; font-size: 36px; padding: 5px; }
  2486.                                 h2 img{width: 200px; height: 200px;}
  2487.                                 h4 { text-align: center; font-size: 12px; padding: 10px; }
  2488.                                 h5 { text-align: center; font-size: 22px; padding: 10px; }
  2489.                                 h6 { text-align: justify; font-size: 26px; padding: 5px; }}
  2490.                                 p { text-align: justify; font-size: 18px; font-weight: bold; padding: 10px; }
  2491.                                 .pai { position: relative; top: 20%;text-align:center; }
  2492.                                 hr { color: black; }
  2493.                                 
  2494.                                     .linha {
  2495.                                         margin-bottom: 1mm;
  2496.                                         font-size: 10pt;
  2497.                                     }
  2498.                                     .box-label {
  2499.                                         background: #f1f1f1;
  2500.                                         border: 1px solid black;
  2501.                                         padding: 1mm;
  2502.                                         font-size: 8pt;
  2503.                                         text-align: center;
  2504.                                         margin-top: 1mm;
  2505.                                     }
  2506.                                     .box-value {
  2507.                                         text-align: center;
  2508.                                         font-size: 10pt;
  2509.                                         margin: 2mm 0 2mm 0;
  2510.                                         
  2511.                                     }
  2512.                                    .box-value_conteudo {
  2513.                                         margin: 2mm 0 2mm 0;
  2514.                                         text-align: justify;
  2515.                                        
  2516.                                     }
  2517.                                     
  2518.                                     img{
  2519.                                         width: 120px;
  2520.                                         height:80px;
  2521.                                         margin: 2mm 0 2mm 0;
  2522.                                     }
  2523.                                     
  2524.                                     .titulo{
  2525.                                         margin: 2mm 0 2mm 0;
  2526.                                         font-size: 10pt;
  2527.                                     }
  2528.                                     
  2529.                                     .bloco-conteudo {
  2530.                                         position: relative;
  2531.                                         height: 100%;
  2532.                                     }
  2533.                                     
  2534.                                     .hr-fixo {
  2535.                                         position: absolute;
  2536.                                         bottom: 0;
  2537.                                         left: 0;
  2538.                                         width: 100%;
  2539.                                         margin: 0 0 0 0;
  2540.                                     }
  2541.                                     
  2542.                                 
  2543.                             </style>
  2544.                         </head>
  2545.                         <body>
  2546.                         <div class="pai">';
  2547.                 
  2548.                         $count = 0;
  2549.                 
  2550.                         foreach ($documento_all_sebrae as $caixa) {
  2551.                             $count++;
  2552.                                 $conteudo = htmlspecialchars(str_replace('?', '', $caixa->getExtraFields()));
  2553.                                 $tamanho = strlen($conteudo);
  2554.                                 $dates="";
  2555.                             
  2556.                                 if ($tamanho <= 300) {
  2557.                                     $fontSize = '8pt';
  2558.                                 } elseif ($tamanho <= 600) {
  2559.                                     $fontSize = '7pt';
  2560.                                 } elseif ($tamanho <= 900) {
  2561.                                     $fontSize = '6pt';
  2562.                                 } else {
  2563.                                     $fontSize = '4pt';
  2564.                                 }
  2565.                                 
  2566.                                 if($caixa->getDataDocumento()){
  2567.                                     $dates=$caixa->getDataDocumento()->format('d/m/Y');
  2568.                                 }
  2569.                             
  2570.                                 $html .= 
  2571.                                     '<div class="filho">
  2572.                                         <div class="bloco-conteudo">
  2573.                                         
  2574.                                             <img src="'.$cliente_all_Url.'" class="img"></h6>
  2575.                             
  2576.                                             <div class="titulo">ARQUIVO INATIVO</div><br>
  2577.                             
  2578.                                             <div class="linha">CAIXA Nº: _______________</div>
  2579.                             
  2580.                                             <div class="box-label">ÁREA/SIGLA:</div>
  2581.                                             <div class="box-value">'. htmlspecialchars($caixa->getAssunto()) .'</div>
  2582.                             
  2583.                                             <div class="box-label">RESPONSÁVEL:</div>
  2584.                                             <div class="box-value">'. htmlspecialchars($caixa->getConteiner()) .'</div>
  2585.                             
  2586.                                             <div class="box-label">DATA 1º ENVIO:</div>
  2587.                                             <div class="box-value">'. htmlspecialchars($dates) .'</div>
  2588.                             
  2589.                                             <div class="box-label">Conteúdo</div>
  2590.                                             <div class="box-value_conteudo" style="font-size: '. $fontSize .'">'. $conteudo .'</div>
  2591.                                             
  2592.                                             <div class="hr-fixo">
  2593.                                                 <hr>
  2594.                                                 <div>CXRBM:'. htmlspecialchars($caixa->getNome()) .'</div>
  2595.                                             </div>
  2596.                             
  2597.                                         </div>
  2598.         </div>';
  2599.                             $docs = [];
  2600.                             if ($count % 2 == 0) {
  2601.                                 $html .= '<div style="page-break-after: always;"></div>';
  2602.                             }
  2603.                         }
  2604.                
  2605.                         $html .= '</div></body></html>';
  2606.                 }
  2607.                         
  2608.                
  2609.                
  2610.                 // Configurar o Dompdf
  2611.                 $options = new Options();
  2612.                 $options->set('isHtml5ParserEnabled', true);
  2613.                 $options->set('isPhpEnabled', true);
  2614.                 $options->set('isRemoteEnabled', true);
  2615.                 $dompdf = new Dompdf($options);
  2616.                 $dompdf->loadHtml($html);
  2617.                 $dompdf->setPaper('A4', 'landscape');
  2618.         
  2619.                 // LIMPA TODOS OS BUFFERS ANTES DE RENDERIZAR
  2620.                 while (ob_get_level()) {
  2621.                     ob_end_clean();
  2622.                 }
  2623.         
  2624.                 // Tenta renderizar e, em vez de stream() direto, grava em arquivo temporário e envia
  2625.                 try {
  2626.                     $dompdf->render();
  2627.                 } catch (Throwable $e) {
  2628.                     // registra o erro e lança para cair no catch externo
  2629.                     error_log('Dompdf render failed: ' . $e->getMessage());
  2630.                     throw $e;
  2631.                 }
  2632.         
  2633.                 // Gera arquivo temporário seguro
  2634.                 $tempFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'etiqueta_fluxo_' . $id_fluxo . '_' . uniqid() . '.pdf';
  2635.                 $output = $dompdf->output();
  2636.         
  2637.                 if (file_put_contents($tempFile, $output) === false) {
  2638.                     throw new Exception('Falha ao escrever arquivo temporário do PDF.');
  2639.                 }
  2640.         
  2641.                 // Força headers corretos para download/visualização
  2642.                 header('Content-Type: application/pdf');
  2643.                 // Se quiser forçar download use attachment; se quiser abrir no browser use inline
  2644.                 header('Content-Disposition: inline; filename="Etiqueta_Fluxo_' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $id_fluxo . '_' . $nome_fluxo) . '.pdf"');
  2645.                 header('Content-Length: ' . filesize($tempFile));
  2646.                 header('Cache-Control: private, max-age=0, must-revalidate');
  2647.         
  2648.                 // Envia o arquivo binário ao navegador
  2649.                 readfile($tempFile);
  2650.         
  2651.                 // Remove o arquivo temporário com segurança
  2652.                 @unlink($tempFile);
  2653.         
  2654.                 // finaliza execução
  2655.                 exit;
  2656.         
  2657.                 
  2658.             } catch (Exception $e) {
  2659.                 // Loga para diagnóstico e mostra mensagem amigável
  2660.                 error_log('Erro ao gerar o PDF: ' . $e->getMessage());
  2661.                 echo 'Erro ao gerar o PDF: ' . htmlspecialchars($e->getMessage());
  2662.             }
  2663.         
  2664.         
  2665.             }
  2666.         if (isset($_POST["qrcode"])) {
  2667.                 $id_fluxo = $_POST["qrcode"];
  2668.                 $fluxo_qrcode = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($_POST["qrcode"]);
  2669.                 $nome_fluxo = $fluxo_qrcode->getNome();
  2670.                 $fluxo_caixas_qrcode = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_qrcode->getId());
  2671.                 $clienteAll_id = $fluxo_qrcode->getCliente()->getId();
  2672.                 
  2673.                 if ($fluxo_caixas_qrcode != null ) {
  2674.                     $options = new Options();
  2675.                     $options->set('isHtml5ParserEnabled', true);
  2676.                     $options->set('isPhpEnabled', true);
  2677.                     $dompdf = new Dompdf($options);
  2678.                             
  2679.                     $html = '
  2680.                         <html>
  2681.                             <head>
  2682.                                 <style>
  2683.                                     @page {
  2684.                                         margin: 35px 18.9px 0px 18.9px;
  2685.                                         size: 210mm 297mm; /* Ajuste de tamanho do papel */
  2686.                                     }
  2687.                                     body {
  2688.                                         margin: 0;
  2689.                                         padding: 0;
  2690.                                     }
  2691.                                     .qr-item {
  2692.                                         border: 2px dotted #000;
  2693.                                         text-align: center;
  2694.                                         width: 32.27mm;
  2695.                                         height: 34.9mm; 
  2696.                                         display: inline-block;
  2697.                                     }
  2698.                         
  2699.                                     .qr-item img {
  2700.                                         width: 115px; 
  2701.                                         height: 112px;
  2702.                                     }
  2703.                                     .qr-title {
  2704.                                         font-size: 16px;
  2705.                                         font-weight: bold;
  2706.                                     }
  2707.                                     .leo {
  2708.                                         display: flex;
  2709.                                         flex-wrap: wrap;
  2710.                                     }
  2711.                                 </style>
  2712.                             </head>
  2713.                             <body>';
  2714.             
  2715.                     $count = 0; // Contador de QR Codes
  2716.             
  2717.                     foreach ($fluxo_caixas_qrcode as $cx) {
  2718.                         $id_cx_ultimo = $cx->getCx();
  2719.             
  2720.                         if ($id_cx_ultimo !== null) {
  2721.                             $nome = $id_cx_ultimo->getNome();
  2722.             
  2723.                             // Gerar QR Code com imagem no centro
  2724.                             $result = Builder::create()
  2725.                                 ->writer(new PngWriter())
  2726.                                 ->writerOptions([])
  2727.                                 ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$nome)
  2728.                                 ->encoding(new Encoding('UTF-8'))
  2729.                                 ->size(500)
  2730.                                 ->margin(5)
  2731.                                 ->logoPath(__DIR__ . '/logo.png') // Caminho do logo central
  2732.                                 ->build();
  2733.                             
  2734.                             // Salvar QR Code como arquivo temporário
  2735.                             $tempFile = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  2736.                             $result->saveToFile($tempFile);
  2737.             
  2738.                             // Adicionar QR Code ao HTML
  2739.                             if ($count % 48 == 0) {
  2740.                                 $html .= '<div class="leo">';
  2741.                             }
  2742.             
  2743.                             $html .= '<div class="qr-item">';
  2744.                             $html .= '<div class="qr-title">' . $nome . '</div>';
  2745.                             $html .= '<img src="data:image/png;base64,' . base64_encode(file_get_contents($tempFile)) . '">';
  2746.                             $html .= '</div>';
  2747.             
  2748.                             $count++;
  2749.             
  2750.                             // Fechar a div e inserir quebra de página a cada 63 QR Codes
  2751.                             if ($count % 48 == 0) {
  2752.                                 $html .= '</div><div style="page-break-after: always;"></div>';
  2753.                             }
  2754.                         }
  2755.                     }
  2756.             
  2757.                     // Fechar qualquer div aberta sem completar 63 itens
  2758.                     if ($count % 48 != 0) {
  2759.                         $html .= '</div>';
  2760.                     }
  2761.             
  2762.                     $html .= '</body></html>';
  2763.             
  2764.                     // Carregar o HTML e gerar o PDF
  2765.                     $dompdf->loadHtml($html);
  2766.                     $dompdf->setPaper([0, 0, 210, 297], 'portrait'); // Configurar o tamanho de página para A4
  2767.                     $dompdf->render();
  2768.                     $dompdf->stream("Qrcode_" . $id_fluxo . "_" . $nome_fluxo . ".pdf", ["Attachment" => 1 ]);
  2769.                 } else {
  2770.                     echo "<script>alert('ERROR, ESSE FLUXO NÃO TEM SETOR DE GUARDA!');</script>";
  2771.                 }
  2772.             }
  2773.         
  2774.         if (isset($_POST["container"])) {
  2775.             $id_fluxo = $_POST["container"];
  2776.             $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($id_fluxo);
  2777.             $fluxo_container = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  2778.             $clienteAll_id = $fluxo_container->getCliente()->getId();
  2779.             $containers = [];
  2780.         
  2781.             foreach ($fluxo_caixas as $caixa) {
  2782.                 $documentos = $caixa->getDocumentos();
  2783.         
  2784.                 foreach ($documentos as $documento) {
  2785.                     $container = $documento->getConteiner(); 
  2786.                     $caixaId = $documento->getCaixa()->getId(); 
  2787.                     
  2788.                     if ($container != null and $caixaId != null) {
  2789.                         
  2790.                         if (!isset($containers[$container])) {
  2791.                             $containers[$container] = [];
  2792.                         }
  2793.         
  2794.                         if (!in_array($caixaId, $containers[$container])) {
  2795.                             $containers[$container][] = $caixaId;
  2796.                         }
  2797.                     }
  2798.                 }
  2799.             }
  2800.             
  2801.             $options = new Options();
  2802.             $options->set('isHtml5ParserEnabled', true);
  2803.             $options->set('isPhpEnabled', true);
  2804.             $dompdf = new Dompdf($options);
  2805.                     
  2806.             $html = '
  2807.                 <html>
  2808.                     <head>
  2809.                         <style>
  2810.                             @page {
  2811.                                 margin: 35px 18.9px 0px 18.9px;
  2812.                                 size: 210mm 297mm; /* Ajuste de tamanho do papel */
  2813.                             }
  2814.                             body {
  2815.                                 margin: 0;
  2816.                                 padding: 0;
  2817.                             }
  2818.                             .qr-item {
  2819.                                 border: 2px dotted #000;
  2820.                                 width: 200mm;
  2821.                                 height: 80mm;
  2822.                                 margin-top:15px; 
  2823.                                 text-align: center;
  2824.                                
  2825.                                 
  2826.                             }
  2827.                              .img_qrcode h2{                           
  2828.                                position:relative;
  2829.                                top:25px;
  2830.                             }
  2831.                             .img_qrcode h3{                           
  2832.                                position:relative;
  2833.                                bottom:25px;
  2834.                                font-size: 20px;
  2835.                             }
  2836.                             .img_qrcode{
  2837.                                
  2838.                                 display: inline-block;
  2839.                                 margin: 5px  30px 5px 30px;
  2840.                                
  2841.                                
  2842.                             }
  2843.                 
  2844.                             .qr-item img {
  2845.                                 
  2846.                                 width: 170px; 
  2847.                                 height: 170px;
  2848.                                 
  2849.                             }
  2850.                             .qr-title {
  2851.                                 font-size: 70px;
  2852.                                 font-weight: bold;
  2853.                                
  2854.                             }
  2855.                             .leo {
  2856.                                 display: flex;
  2857.                                 flex-wrap: wrap;
  2858.                             }
  2859.                         </style>
  2860.                     </head>
  2861.                     <body>';
  2862.     
  2863.             $count = 0; // Contador de QR Codes
  2864.             // Exibir resultado
  2865.             foreach ($containers as $container => $caixas) {
  2866.                 #echo "Container $container => " . implode(", ", $caixas) . "<br>";
  2867.                 
  2868.                
  2869.                 if ($count % 3 == 0) {
  2870.                     $html .= '<div class="leo">';
  2871.                 }
  2872.                 $html .= '<div class="qr-item">';
  2873.                 $html .= '<div class="qr-title">' . $container . '</div><hr>';
  2874.                 foreach($caixas as $caixa ){
  2875.                     $caix = $doctrine->getRepository(Caixa::class)->find($caixa);
  2876.                     $caix_nome =$caix->getNome();
  2877.                     $caix_cx =$caix->getCx()->getNome();
  2878.                     $result = Builder::create()
  2879.                     ->writer(new PngWriter())
  2880.                     ->writerOptions([])
  2881.                     ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$caix_cx)
  2882.                     ->encoding(new Encoding('UTF-8'))
  2883.                     ->size(350)
  2884.                     ->margin(5)
  2885.                     ->logoPath(__DIR__ . '/logo.png') 
  2886.                     ->build();
  2887.                 
  2888.                 
  2889.                     $tempFile = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  2890.                     $result->saveToFile($tempFile);
  2891.                     
  2892.                     $html .= '
  2893.                         <div class="img_qrcode">    
  2894.                             <h2>'.$caix_cx.'</h2>
  2895.                             <img src="data:image/png;base64,' . base64_encode(file_get_contents($tempFile)) . '">
  2896.                             <h3>'.$caix_nome.'</h3>
  2897.                         </div>
  2898.                     
  2899.                     ';
  2900.                 }
  2901.                 $html .= '</div>';
  2902.                 $count++;
  2903.                 
  2904.                 if ($count % 3 == 0) {
  2905.                     $html .= '</div><div style="page-break-after: always;"></div>';
  2906.                 }
  2907.             }
  2908.               // Fechar qualquer div aberta sem completar 63 itens
  2909.               if ($count % 3 != 0) {
  2910.                 $html .= '</div>';
  2911.             }
  2912.     
  2913.             $html .= '</body></html>';
  2914.     
  2915.             // Carregar o HTML e gerar o PDF
  2916.             $dompdf->loadHtml($html);
  2917.             $dompdf->setPaper([0, 0, 210, 297], 'portrait'); // Configurar o tamanho de página para A4
  2918.             $dompdf->render();
  2919.             $dompdf->stream("Qrcode.pdf", ["Attachment" => 1 ]);
  2920.             
  2921.         }
  2922.         
  2923.         if (isset($_POST["pasta"])) {
  2924.             
  2925.                 // reforça limites (pode ajustar conforme necessário)
  2926.                 ini_set('max_execution_time', 500);
  2927.                 ini_set('memory_limit', '3512M');
  2928.         
  2929.                 $id_fluxo = $_POST["pasta"];
  2930.                 $fluxo_pdf = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($id_fluxo);
  2931.                 $cliente_id = $fluxo_pdf->getCliente()->getId();
  2932.                 $cliente = $doctrine->getRepository(Cliente::class)->findWithRelations($cliente_id);
  2933.                 $nome_fluxo = $fluxo_pdf->getNome();
  2934.                 $clienteAll_fluxo = $cliente->getClienteAll()->getLogo();
  2935.                 
  2936.                 $cmd = $clientS3->getCommand('GetObject', [
  2937.                 'Bucket' => 'arquivosdoc',
  2938.                 'Key'    => 'LOGO_CLIENTES/'. $clienteAll_fluxo, 
  2939.                 ]);
  2940.                 
  2941.                 $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  2942.                 $cliente_all_Url = (string) $req->getUri();
  2943.                 
  2944.                 $clienteAll_fluxo_id = $cliente->getClienteAll()->getId();
  2945.                 $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_pdf->getId());
  2946.                 if($clienteAll_fluxo_id == 39){
  2947.                     $html = '
  2948.                     <!DOCTYPE html>
  2949.                     <html lang="pt-BR">
  2950.                     <head>
  2951.                         <meta charset="UTF-8">
  2952.                         <meta name="viewport" content="width=device-width, initial-scale=1.0">
  2953.                         <title>FLUXO</title>
  2954.                         <style>
  2955.                             * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  2956.                             body { text-transform: uppercase; }
  2957.                             .filho { border: 2px solid black; width: 67.8mm; height: 145mm; display: inline-block; margin: 0px 2px 2px 2px; position: relative; }
  2958.                             h2 { text-align: center; font-size: 30px; padding: 5px; }
  2959.                             h2 img{width: 250px; height: 250px;}
  2960.                             h4 { text-align: center; font-size: 14px; padding: 10px; }
  2961.                             h5 { text-align: center; font-size: 16px;}
  2962.                             h6 { text-align: center; font-size: 18px; padding: 20px; }
  2963.                             h5 img { text-align: center;max-height: 40px;width:auto;max-width: 40px}
  2964.                             h6 img { text-align: center;margin:auto;  max-height: 200px;width:auto;max-width: 200px}
  2965.                             p { text-align: center; font-size: 12px; font-weight: bold;}
  2966.                             .pai { position: relative; top: 11%; }
  2967.                             hr { color: black; }
  2968.                             .lis2{
  2969.                                         
  2970.                                 font-weight: bold;
  2971.                                 margin:5px;
  2972.                             }
  2973.                             .lis3 {
  2974.                                 position: absolute;
  2975.                                 bottom: 0;
  2976.                                 width: 100%;
  2977.                                 font-weight: bold;
  2978.                                 text-align: center;
  2979.                                 margin-bottom:5px;
  2980.                                 margin-top:5px;
  2981.                             }
  2982.                             .lis{
  2983.                                 
  2984.                                 margin-left:10px;
  2985.                                 font-weight: bold;
  2986.                             }
  2987.                             li{
  2988.                                 margin:10px;
  2989.                                 font-size: 18px;
  2990.                             }
  2991.                             
  2992.                         </style>
  2993.                     </head>
  2994.                     <body>
  2995.                     <div class="pai">';
  2996.             
  2997.                     $count = 0;
  2998.             
  2999.                     foreach ($fluxo_caixas as $caixa) {
  3000.                         $count++;
  3001.                         $documento_fluxo = $caixa->getDocumentos()->toArray();
  3002.                         
  3003.                         
  3004.                         $html .= '<div class="filho">
  3005.                             
  3006.                             
  3007.                             <h6><img src="'.$cliente_all_Url.'" class="img"></h6>
  3008.                             <hr>
  3009.                             <h2>' . htmlspecialchars($caixa->getNome()) . '</h2>
  3010.                             <hr>
  3011.                             ';
  3012.             
  3013.                         $docs = [];
  3014.                         
  3015.                         if (!empty($documento_fluxo)) {
  3016.                             foreach ($documento_fluxo as $doc) {
  3017.                                 if($doc->getTipo() != NULL ){
  3018.                                     if ($cliente_id != 122) {
  3019.                                         $docs[] = $doc->getTipo()->getNome();
  3020.                                     } else {
  3021.                                         $docs[] = $doc->getNome();
  3022.                                     }
  3023.                                 }
  3024.                             }
  3025.                             $docs = array_unique($docs);
  3026.                         }
  3027.                         
  3028.                         $docs_class = [];
  3029.                         
  3030.                         if (!empty($documento_fluxo)) {
  3031.                             foreach ($documento_fluxo as $doc) {
  3032.                                 
  3033.                                 if($doc->getClassificacao() != NULL ){
  3034.                                     $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  3035.                                     $class_nome =  $clss[0]->getNome();
  3036.                                     $docs_class[] = $class_nome;
  3037.                                     
  3038.                                 }
  3039.                             }
  3040.                             $docs_class = array_unique($docs_class);
  3041.                         }
  3042.                         $docs_data = [];
  3043.                         $mapa = [];
  3044.                         if (!empty($documento_fluxo)) {
  3045.                             foreach ($documento_fluxo as $data) {
  3046.                                 if ($data->getNome() != null) {
  3047.                                     $docs_data[] = $data->getNome();
  3048.                                 }
  3049.                             }
  3050.                             $docs_data = array_unique($docs_data);
  3051.                         }
  3052.                         $numeros = [];
  3053.                         foreach ($docs_data as $doc) {
  3054.                             if (preg_match('/PL-(\d+)/', $doc, $matches)) {
  3055.                                 $numero = (int) $matches[1];
  3056.                                 $numeros[] = $numero;
  3057.                                 $mapa[$numero] = $doc; // ✅ CORRETO
  3058.                             }
  3059.                         }
  3060.                         if (!empty($numeros)) {
  3061.                             $menor = min($numeros);
  3062.                             $maior = max($numeros);
  3063.                             $menorNome = $mapa[$menor];
  3064.                             $maiorNome = $mapa[$maior];
  3065.                         } else {
  3066.                             $menor = null;
  3067.                             $maior = null;
  3068.                             $menorNome = null;
  3069.                             $maiorNome = null;
  3070.                         }
  3071.                         /* Sequência completa e faltantes */
  3072.                         $sequenciaCompleta = range($menor, $maior);
  3073.                         $faltantes = array_diff($sequenciaCompleta, $numeros);
  3074.                         /* Nomes faltantes */
  3075.                         $docs_faltantes = [];
  3076.                         
  3077.                         if($docs_faltantes != []){
  3078.                             foreach ($faltantes as $num) {
  3079.                                 $docs_faltantes[] = 'PL_' . str_pad($num, 3, '0', STR_PAD_LEFT);
  3080.                             }
  3081.                         }
  3082.                         
  3083.                                                     
  3084.                         
  3085.                         
  3086.                         $html .= '<h6>' . htmlspecialchars(implode(', ', $docs)) . '</h6>
  3087.                             <hr>';
  3088.                             
  3089.                             $html .= '<h6>Conteúdo:</h6>';
  3090.                             $html .= '<div class="lis">';
  3091.                             foreach ($docs_class as $classs_nome) {
  3092.                             $html .= '
  3093.                                 <li>' . $classs_nome. '</li>';
  3094.                             }
  3095.                             $html .= '</div>';
  3096.                             $html .= '<h6>'.$menorNome.' Até '.$maiorNome.'</h6>';
  3097.                             if($docs_faltantes != []){
  3098.                                 $html .= '<div class="lis2"><p>';
  3099.                                     
  3100.                                         foreach ($docs_faltantes as $data) {
  3101.                                             $html .= 'Faltantes*: | ' . $data. ' | ';
  3102.                                         }
  3103.                                     
  3104.                                 $html .= '</p></div>';
  3105.                             }
  3106.                             /*$html .= '
  3107.                                     <div class="lis3"><hr>
  3108.                                     
  3109.                                     <p>ARQUIVOS GESTÃO DOCUMENTAL</p>
  3110.                                     <h5><img src="https://index.arquivosdoc.com.br/img/logo_menu.png" class="img"></h5>
  3111.                                     </div>
  3112.                                     
  3113.                                 </div>';*/
  3114.                             
  3115.                             $html .= '</div>';
  3116.             
  3117.                         if ($count %  6 == 0) {
  3118.                             $html .= '<div style="page-break-after: always;"></div>';
  3119.                         }
  3120.                     }
  3121.             
  3122.                     $html .= '</div></body></html>';
  3123.                 }
  3124.                 
  3125.                 if($clienteAll_fluxo_id == 41){
  3126.                      $html = '
  3127.                             <!DOCTYPE html>
  3128.                             <html lang="pt-BR">
  3129.                             <head>
  3130.                                 <meta charset="UTF-8">
  3131.                                 <meta name="viewport" content="width=device-width, initial-scale=1.0">
  3132.                                 <title>FLUXO</title>
  3133.                                 <style>
  3134.                                     * { margin: 0; padding: 0; font-family: Calibri, Arial, sans-serif; }
  3135.                                     body { text-transform: uppercase; }
  3136.                                     .filho { border: 2px solid black; width: 50mm; height: 144mm; display: inline-block; margin: 2px; position: relative;}
  3137.                                     h2 { text-align: center; font-size: 20px; padding: 5px; }
  3138.                                     h2 img{width: 250px; height: 250px;}
  3139.                                     h4 { text-align: center; font-size: 12px; padding: 10px; }
  3140.                                     h5 { text-align: center; font-size: 14px;}
  3141.                                     h6 { text-align: center; font-size: 14px; padding: 5px; }
  3142.                                     h5 img { text-align: center;max-height: 40px;width:auto;max-width: 40px}
  3143.                                     h6 img { text-align: center;margin:auto;  max-height: 130px;width:auto;max-width: 130px}
  3144.                                     p { text-align: center; font-size: 8px; font-weight: bold;}
  3145.                                     .pai { position: relative; top: 11%; }
  3146.                                     hr { color: black; }
  3147.                                     .lis2{
  3148.                                         
  3149.                                         font-weight: bold;
  3150.                                     }
  3151.                                     .lis3 {
  3152.                                         position: absolute;
  3153.                                         bottom: 0;
  3154.                                         width: 100%;
  3155.                                         font-weight: bold;
  3156.                                         text-align: center;
  3157.                                         margin-bottom:5px;
  3158.                                         margin-top:5px;
  3159.                                            
  3160.                                     }
  3161.                                     .lis{
  3162.                                         
  3163.                                         margin-left:10px;
  3164.                                         font-weight: bold;
  3165.                                     }
  3166.                                     li{
  3167.                                        font-size: 12px;
  3168.                                        margin-left:2px;
  3169.                                     }
  3170.                                     
  3171.                                 </style>
  3172.                             </head>
  3173.                             <body>
  3174.                             <div class="pai">';
  3175.             
  3176.                     $count = 0;
  3177.             
  3178.                     
  3179.                             foreach ($fluxo_caixas as $caixa) {
  3180.                                 $count++;
  3181.                                 $documento_fluxo = $caixa->getDocumentos()->toArray();
  3182.                                 
  3183.                     
  3184.                                 $html .= '<div class="filho">
  3185.                                     
  3186.                                     
  3187.                                     <h6><img src="'.$cliente_all_Url.'" class="img"></h6>
  3188.                                     <hr>
  3189.                                     <h2>' . htmlspecialchars($caixa->getNome()) . '</h2>
  3190.                                     <hr>
  3191.                                     ';
  3192.                     
  3193.                                 $docs = [];
  3194.                                 
  3195.                                 if (!empty($documento_fluxo)) {
  3196.                                     foreach ($documento_fluxo as $doc) {
  3197.                                         if($doc->getTipo() != NULL ){
  3198.                                             if ($cliente_id != 122) {
  3199.                                                 $docs[] = $doc->getTipo()->getNome();
  3200.                                             } else {
  3201.                                                 $docs[] = $doc->getNome();
  3202.                                             }
  3203.                                         }
  3204.                                     }
  3205.                                     $docs = array_unique($docs);
  3206.                                 }
  3207.                                 
  3208.                                 
  3209.     
  3210.     
  3211.                                 $docs_class = [];
  3212.                                 
  3213.                                 if (!empty($documento_fluxo)) {
  3214.                                     foreach ($documento_fluxo as $doc) {
  3215.                                         
  3216.                                         if($doc->getClassificacao() != NULL ){
  3217.                                            $clss =  $entityManager->getRepository(Classificacao::class)->findBy(['id' => $doc->getClassificacao()->getId()]);
  3218.                                            $class_nome =  $clss[0]->getNome();
  3219.                                            $docs_class[] = $class_nome;
  3220.                                             
  3221.                                         }
  3222.                                     }
  3223.                                     $docs_class = array_unique($docs_class);
  3224.                                 }
  3225.                     
  3226.     
  3227.                                   $docs_data = [];
  3228.                                   if (!empty($documento_fluxo)) {
  3229.                                         foreach ($documento_fluxo as $data) {
  3230.                                             if ($data->getAssunto() !== null) {
  3231.                                                 $docs_data[] = $data->getAssunto();
  3232.                                             }
  3233.                                         }
  3234.                                         $docs_data = array_unique($docs_data);
  3235.                                     }
  3236.                                 
  3237.                               
  3238.     
  3239.                                 
  3240.     
  3241.     
  3242.                                                             
  3243.                                 
  3244.                                 
  3245.                                 $html .= '<h6>' . htmlspecialchars(implode(', ', $docs)) . '</h6>
  3246.                                     <hr>';
  3247.                                    
  3248.     
  3249.     
  3250.                                     $html .= '<h6>Conteúdo:</h6>';
  3251.     
  3252.                                     $html .= '<div class="lis">';
  3253.                                     foreach ($docs_class as $classs_nome) {
  3254.                                     if($classs_nome == '028.11-COM ÔNUS'){
  3255.                                      $html .= '<li>SOLICITAÇÃO DE DIÁRIAS</li>';
  3256.                                     }
  3257.                                     $html .= '
  3258.                                         <li>' . $classs_nome. '</li>';
  3259.                                     }
  3260.                                     $html .= '</div><br>';
  3261.                                     $html .= '<h6>Descrição:</h6>';
  3262.                                     $html .= '<div class="lis">';
  3263.                                     $len = count($docs_data);
  3264.                                     foreach ($docs_data as $assunto_nome) {
  3265.                                         
  3266.                                     $qtd_letra = mb_strlen($assunto_nome, 'UTF-8');
  3267.                                      
  3268.                                     if ($len <= 20) {
  3269.                                         $fontSize = 12;
  3270.                                     } 
  3271.                                     
  3272.                                     else{
  3273.                                         $fontSize = 9;
  3274.                                     }
  3275.                                     if($qtd_letra > 25 ){
  3276.                                         $fontSize = 10;
  3277.                                     }
  3278.                                     $html .= '<li style="font-size: ' . $fontSize . 'px;">' . $assunto_nome. '</li>';
  3279.                                     }
  3280.                                     $html .= '</div><br>
  3281.                                     <div class="lis3"><hr>
  3282.                                     
  3283.                                     <p>ARQUIVOS GESTÃO DOCUMENTAL</p>
  3284.                                     <h5><img src="https://index.arquivosdoc.com.br/img/logo_menu.png" class="img"></h5>
  3285.                                     </div>
  3286.                                     
  3287.                                 </div>';
  3288.                     
  3289.                                 #if ($count == 4) {
  3290.                                  #   $html .= '<div style="page-break-after: always;"></div>';
  3291.                                 #}
  3292.                             }
  3293.                    
  3294.     
  3295.                     
  3296.                     
  3297.             
  3298.     
  3299.                     $html .= '</div></body></html>';
  3300.                 }
  3301.         
  3302.                 // Configurar o Dompdf
  3303.                 $options = new Options();
  3304.                 $options->set('isHtml5ParserEnabled', true);
  3305.                 $options->set('isPhpEnabled', true);
  3306.                 $options->set('isRemoteEnabled', true);
  3307.                 $dompdf = new Dompdf($options);
  3308.                 $dompdf->loadHtml($html);
  3309.                 $dompdf->setPaper('A4', 'portrait');
  3310.         
  3311.                 // LIMPA TODOS OS BUFFERS ANTES DE RENDERIZAR
  3312.                 while (ob_get_level()) {
  3313.                     ob_end_clean();
  3314.                 }
  3315.         
  3316.                 // Tenta renderizar e, em vez de stream() direto, grava em arquivo temporário e envia
  3317.                 try {
  3318.                     $dompdf->render();
  3319.                 } catch (Throwable $e) {
  3320.                     // registra o erro e lança para cair no catch externo
  3321.                     error_log('Dompdf render failed: ' . $e->getMessage());
  3322.                     throw $e;
  3323.                 }
  3324.         
  3325.                 // Gera arquivo temporário seguro
  3326.                 $tempFile = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'etiqueta_fluxo_' . $id_fluxo . '_' . uniqid() . '.pdf';
  3327.                 $output = $dompdf->output();
  3328.         
  3329.                 if (file_put_contents($tempFile, $output) === false) {
  3330.                     throw new Exception('Falha ao escrever arquivo temporário do PDF.');
  3331.                 }
  3332.         
  3333.                 // Força headers corretos para download/visualização
  3334.                 header('Content-Type: application/pdf');
  3335.                 // Se quiser forçar download use attachment; se quiser abrir no browser use inline
  3336.                 header('Content-Disposition: inline; filename="Etiqueta_Fluxo_' . preg_replace('/[^A-Za-z0-9_\-\.]/', '_', $id_fluxo . '_' . $nome_fluxo) . '.pdf"');
  3337.                 header('Content-Length: ' . filesize($tempFile));
  3338.                 header('Cache-Control: private, max-age=0, must-revalidate');
  3339.         
  3340.                 // Envia o arquivo binário ao navegador
  3341.                 readfile($tempFile);
  3342.         
  3343.                 // Remove o arquivo temporário com segurança
  3344.                 @unlink($tempFile);
  3345.         
  3346.                 // finaliza execução
  3347.                 exit;
  3348.         
  3349.                 
  3350.        
  3351.         
  3352.         }
  3353.        
  3354.         
  3355.         return $this->render('index/index5.html.twig', [
  3356.             'clienteAll' => $cliente->getClienteAll()->getId(),
  3357.             'fluxos' => $fluxos,
  3358.             'p'=>$p,
  3359.             'erro'=>$erro,
  3360.             'pagina' => $pagina,
  3361.             'a' => $a,
  3362.              
  3363.         ]);
  3364.     }
  3365.     
  3366.     
  3367.     #[Route('/index/fluxo/diagrama/{id}', name: 'diagrama')]
  3368.     public function diagrama( PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer,$id): Response
  3369.     {
  3370.         $user_logado = $this->getUser();
  3371.         $erro = '';
  3372.         $pagina = 'fluxo';
  3373.         $p ='';
  3374.         $clienteId = $session->get('cliente_id');
  3375.         
  3376.         if($clienteId == null){
  3377.             
  3378.             return $this->redirectToRoute('home');
  3379.         }
  3380.         
  3381.         $fluxo_diagrama = $doctrine->getRepository(Fluxo::class)->find($id);
  3382.         $fluxo_caixas_diagrama = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo_diagrama->getId());
  3383.             
  3384.  
  3385.     
  3386.         return $this->render('index/diagrama.html.twig', [
  3387.     
  3388.             'p'=>$p,
  3389.             'erro'=>$erro,
  3390.             'pagina' => $pagina,
  3391.             "fluxo_diagrama" => $fluxo_diagrama,
  3392.             "fluxo_caixas_diagrama" => $fluxo_caixas_diagrama
  3393.              
  3394.         ]);
  3395.     }
  3396.     #[Route('/index/recebimento/{id}', name: 'recebimento')]
  3397.     public function recebimento( PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer,$id): Response
  3398.     {
  3399.         $user_logado = $this->getUser();
  3400.         $user_nome = $user_logado->getNome();
  3401.         $ip_cliente = $_SERVER['REMOTE_ADDR'];
  3402.         $erro = '';
  3403.         $pagina = 'home';
  3404.         $p ='';
  3405.         $ged = ""; 
  3406.         $log = "";
  3407.         $caixa_manual = "";
  3408.         $caixa_auto = "";
  3409.         $cx_ultimo = $doctrine->getRepository(Cx::class)->findUltimo();
  3410.         $etapa = $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  3411.         $fluxo = $etapa->getFluxo();
  3412.         $cliente_fluxo = $fluxo->getCliente()->getId();
  3413.         $clienteId = $session->get('cliente_id');
  3414.         $cliente = $doctrine->getRepository(Cliente::class)->findWithRelations($cliente_fluxo);
  3415.         $clienteAll =  $cliente->getClienteAll();
  3416.         $cliente_nome =  $cliente->getNome();
  3417.         $clienteAll_id =  $clienteAll->getId();
  3418.         $count = 0; // Contador de QR Codes
  3419.         $id_cx_ultimo = 0;
  3420.         $date_hoje = new \DateTimeImmutable('America/Sao_Paulo');
  3421.         
  3422.         $caixas_setor = $entityManager->getRepository(Cliente::class)->findCaixasByClienteId($cliente_fluxo);
  3423.         
  3424.         $query = $entityManager->createQuery("
  3425.             SELECT c FROM App\Entity\Cx c
  3426.             LEFT JOIN c.caixas cx
  3427.             WHERE c.cliente = :clienteId
  3428.             AND cx.id IS NULL
  3429.         ");
  3430.         $query->setParameter('clienteId', $clienteAll_id);
  3431.         $cx_setor = $query->getResult();
  3432.         foreach ($cx_ultimo as $key_id) {
  3433.             
  3434.             $id_cx_ultimo = $key_id->getNome();
  3435.         }
  3436.         
  3437.         if(isset($_POST["btn_cliente"])){
  3438.             
  3439.             $session->set('cliente_id', $_POST["btn_cliente"]);
  3440.             return $this->redirectToRoute('home');
  3441.         }
  3442.         
  3443.         if($clienteId == null){
  3444.             
  3445.             return $this->redirectToRoute('home');
  3446.         }
  3447.         
  3448.         if ($request->isMethod('POST')) {
  3449.             
  3450.           
  3451.             
  3452.             if(isset($_POST["tipo"])){
  3453.                  $tp = $_POST["tipo"];
  3454.                
  3455.                if($tp =='caixa'){
  3456.                    
  3457.                     if($_POST["qtd_caixa"] != ""){
  3458.     
  3459.     
  3460.                         if (isset($_POST["ged"]) || isset($_POST["log"])) {
  3461.     
  3462.                                 if (isset($_POST["ged"])) {
  3463.                                     
  3464.                                     $ged = "ok";
  3465.     
  3466.                                     if (isset($_POST["caixa_manual"]) || isset($_POST["caixa_auto"])) {
  3467.     
  3468.                                         if (isset($_POST["caixa_manual"])) {
  3469.     
  3470.                                             $caixa_manual = "ok";
  3471.             
  3472.                                         }
  3473.                                         if (isset($_POST["caixa_auto"])) {
  3474.     
  3475.                                             $caixa_auto = "ok";
  3476.             
  3477.                                         }
  3478.     
  3479.                                     }else{
  3480.                                         echo "<script>alert('ERROR , Selecione o modo de Identificação do ArquivosGED (Manual ou Automático)!');</script>";
  3481.                                     }
  3482.             
  3483.                                 }
  3484.     
  3485.     
  3486.     
  3487.                                 if (isset($_POST["log"])) {
  3488.     
  3489.                                     $log = "ok";
  3490.                                     
  3491.     
  3492.                                 }
  3493.     
  3494.                                 if ($ged == "ok" and $caixa_manual =="ok") {
  3495.     
  3496.                                     $caixa = $_POST["caixa"];
  3497.                                     $qtd_caixas = 0;
  3498.     
  3499.     
  3500.                                     $options = new Options();
  3501.                                     $options->set('isHtml5ParserEnabled', true);
  3502.                                     $options->set('isPhpEnabled', true);
  3503.                                     $dompdf = new Dompdf($options);
  3504.                         
  3505.                                     $html = '
  3506.                                     <html>
  3507.                                         <head>
  3508.                                             <style>
  3509.                                                 @page {
  3510.                                                     margin: 35px 18.9px 0px 18.9px;
  3511.                                                     size: 210mm 297mm; /* Ajuste de tamanho do papel */
  3512.                                                 }
  3513.                         
  3514.                                                 body {
  3515.                                                     margin: 0;
  3516.                                                     padding: 0;
  3517.                                                 }
  3518.                                                 
  3519.                                                 .qr-item {
  3520.                                                     border: 2px dotted #000;
  3521.                                                     text-align: center;
  3522.                                                     width: 32.27mm;
  3523.                                                     height: 34.9mm; 
  3524.                                                     display: inline-block;
  3525.                                                 }
  3526.                                     
  3527.                                                 .qr-item img {
  3528.                                                     width: 115px; 
  3529.                                                     height: 112px;
  3530.                                                 }
  3531.                         
  3532.                                                 .qr-title {
  3533.                                                     font-size: 16px;
  3534.                                                     font-weight: bold;
  3535.                                                 }
  3536.                         
  3537.                                                 .leo {
  3538.                                                     display: flex;
  3539.                                                     flex-wrap: wrap;
  3540.                                                 }
  3541.                                             </style>
  3542.                                         </head>
  3543.                                         <body> 
  3544.                                       
  3545.                                     ';
  3546.                         
  3547.                         
  3548.                                     
  3549.                                     foreach ($caixa as $key) {
  3550.     
  3551.                                         if ($key != "" ) {
  3552.                                             $qtd_caixas ++ ;
  3553.                                             $caixas = new Caixa();
  3554.                                            
  3555.                                            
  3556.                                             if ($ged == "ok" and $log =="ok") {
  3557.                                                 
  3558.                                                 $cx = new Cx();
  3559.                                                 $id_cx_ultimo ++;
  3560.                                                 $cx->setNome($id_cx_ultimo);
  3561.                                                 $cx->setStatus(2);
  3562.                                                 $cx->setTexto($key);
  3563.                                                 $cx->setImage('ArquivosGED');
  3564.                                                 $cx->setCliente($clienteAll);
  3565.                                                 $entityManager->persist($cx);
  3566.                                                 $entityManager->flush();
  3567.     
  3568.                                                 $id_cx=$cx->getId();
  3569.                                                 $caixas->setCx($entityManager->getRepository(Cx::class)->find($id_cx));
  3570.     
  3571.                                                 // Gerar QR Code com imagem no centro
  3572.                                                 $result = Builder::create()
  3573.                                                 ->writer(new PngWriter())
  3574.                                                 ->writerOptions([])
  3575.                                                 ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  3576.                                                 ->encoding(new Encoding('UTF-8'))
  3577.                                                 ->size(500)
  3578.                                                 ->margin(5)
  3579.                                                 ->logoPath(__DIR__ . '/logo.png') // Caminho do logo central
  3580.                                                 ->build();
  3581.                                                 // Salvar QR Code como arquivo temporário
  3582.                                                 $tempFile = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  3583.                                                 $result->saveToFile($tempFile);
  3584.                                                 
  3585.                                                 // Adicionar QR Code ao HTML
  3586.                                                 if ($count % 48 == 0) {
  3587.                                                     $html .= '<div class="leo">';
  3588.                                                 }
  3589.                                 
  3590.                                                 // Adicionar QR Code ao HTML
  3591.                                                 $html .= '<div class="qr-item">';
  3592.                                                 $html .= '<div class="qr-title">' . $id_cx_ultimo . '</div>';
  3593.                                                 $html .= '<img src="data:image/png;base64,' . base64_encode(file_get_contents($tempFile)) . '">';
  3594.                                                 $html .= '</div>';
  3595.                                                 
  3596.                                                 
  3597.                                                  $count++;
  3598.     
  3599.                                                // Fechar a div e inserir quebra de página a cada 63 QR Codes
  3600.                                                if ($count % 48 == 0) {
  3601.                                                    $html .= '</div><div style="page-break-after: always;"></div>';
  3602.                                                }
  3603.                                                 
  3604.                                             }
  3605.     
  3606.                                             
  3607.                                             $caixas->setNome($key);
  3608.                                             $caixas->addCliente($cliente);
  3609.                                             $caixas->setFluxo($fluxo);
  3610.                                             $entityManager->persist($caixas);
  3611.                                             $entityManager->flush();
  3612.                                             $id_caixa = $caixas->getId();
  3613.                                             
  3614.                                                 
  3615.                                         }
  3616.                                     }
  3617.                                         if ($ged == "ok" and $log =="ok") {
  3618.                                             
  3619.                                               // Fechar qualquer div aberta sem completar 63 itens
  3620.                                              if ($count % 48 != 0) {
  3621.                                                 $html .= '</div>';
  3622.                                             }
  3623.     
  3624.                                             $html .= '</div></body></html>';
  3625.                                 
  3626.                                             // Carregar o HTML e gerar o PDF
  3627.                                             $dompdf->loadHtml($html);
  3628.                                             $dompdf->setPaper([0, 0, 210, 297], 'portrait'); // Configurar o tamanho de página para A4
  3629.                                             $dompdf->render();
  3630.                                             #file_put_contents('sample1.pdf', $dompdf->output());
  3631.                                             $dompdf->stream('dompdf', array('Attachment' => 0));
  3632.                                         }
  3633.     
  3634.                                             $registro = new Registro();
  3635.                                             $registro->setOperacao('RECEBIMENTO DE '.$qtd_caixas. ' CAIXA(S)'); 
  3636.                                             $registro->setUser($user_nome);
  3637.                                             $registro->setCliente($cliente_nome);
  3638.                                             $registro->setIp($ip_cliente);
  3639.                                             $entityManager->persist($registro);
  3640.                                             $entityManager->flush();
  3641.     
  3642.                                             $etapa->setRegistro($registro);
  3643.                                             $etapa->setObs($_POST["obs_caixa"]);
  3644.                                             $etapa->setUpdatedAt($date_hoje);
  3645.                                             $entityManager->flush();
  3646.                                             $erro = 'ok';
  3647.                                             $p = "Recbimento com sucesso";
  3648.                                     
  3649.     
  3650.                                 }
  3651.     
  3652.                                 if ($ged == "ok" and $caixa_auto =="ok") {
  3653.     
  3654.                                     
  3655.                                     if (isset($_POST["auto_ged"])) {
  3656.     
  3657.                                         $qtd_nome_caixa = $_POST["qtd_caixa"];
  3658.                                         $nome_caixa_parti = $_POST["auto_ged"];
  3659.                                         
  3660.     
  3661.     
  3662.     
  3663.                                         $options = new Options();
  3664.                                         $options->set('isHtml5ParserEnabled', true);
  3665.                                         $options->set('isPhpEnabled', true);
  3666.                                         $dompdf = new Dompdf($options);
  3667.                             
  3668.                                         $html = '
  3669.                                         <html>
  3670.                                             <head>
  3671.                                                 <style>
  3672.                                                     @page {
  3673.                                                         margin: 35px 18.9px 0px 18.9px;
  3674.                                                         size: 210mm 297mm; /* Ajuste de tamanho do papel */
  3675.                                                     }
  3676.                             
  3677.                                                     body {
  3678.                                                         margin: 0;
  3679.                                                         padding: 0;
  3680.                                                     }
  3681.                                                     
  3682.                                                    .qr-item {
  3683.                                                     border: 2px dotted #000;
  3684.                                                     text-align: center;
  3685.                                                     width: 32.27mm;
  3686.                                                     height: 34.9mm; 
  3687.                                                     display: inline-block;
  3688.                                                 }
  3689.                                     
  3690.                                                 .qr-item img {
  3691.                                                     width: 115px; 
  3692.                                                     height: 112px;
  3693.                                                 }
  3694.                                     
  3695.                                                     .qr-title {
  3696.                                                         font-size: 16px;
  3697.                                                         font-weight: bold;
  3698.                                                     }
  3699.                             
  3700.                                                     .leo {
  3701.                                                         display: flex;
  3702.                                                         flex-wrap: wrap;
  3703.                                                     }
  3704.                                                 </style>
  3705.                                             </head>
  3706.                                             <body> 
  3707.                                               
  3708.                                         ';
  3709.                         
  3710.                         
  3711.     
  3712.     
  3713.                                         for ($i=0; $i < $qtd_nome_caixa; $i++) { 
  3714.                                             
  3715.                                             $caixas = new Caixa();
  3716.     
  3717.                                             if ($ged == "ok" and $log =="ok") {
  3718.                                                 
  3719.                                                 $cx = new Cx();
  3720.                                                 $id_cx_ultimo ++;
  3721.                                                 $cx->setNome($id_cx_ultimo);
  3722.                                                 $cx->setStatus(2);
  3723.                                                 $cx->setTexto('Caixa '.$nome_caixa_parti);
  3724.                                                 $cx->setImage('ArquivosGED');
  3725.                                                 $cx->setCliente($clienteAll);
  3726.                                                 $entityManager->persist($cx);
  3727.                                                 $entityManager->flush();
  3728.     
  3729.                                                 $id_cx=$cx->getId();
  3730.                                                 $caixas->setCx($entityManager->getRepository(Cx::class)->find($id_cx));
  3731.     
  3732.                                                   // Gerar QR Code com imagem no centro
  3733.                                                 $result = Builder::create()
  3734.                                                   ->writer(new PngWriter())
  3735.                                                   ->writerOptions([])
  3736.                                                   ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  3737.                                                   ->encoding(new Encoding('UTF-8'))
  3738.                                                   ->size(500)
  3739.                                                   ->margin(5)
  3740.                                                   ->logoPath(__DIR__ . '/logo.png') // Caminho do logo central
  3741.                                                   ->build();
  3742.                                                   // Salvar QR Code como arquivo temporário
  3743.                                                   $tempFile = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  3744.                                                   $result->saveToFile($tempFile);
  3745.                                                     
  3746.                                                 // Adicionar QR Code ao HTML
  3747.                                                     if ($count % 48 == 0) {
  3748.                                                         $html .= '<div class="leo">';
  3749.                                                     }    
  3750.                                                     
  3751.                                                   // Adicionar QR Code ao HTML
  3752.                                                   $html .= '<div class="qr-item">';
  3753.                                                   $html .= '<div class="qr-title">' . $id_cx_ultimo . '</div>';
  3754.                                                   $html .= '<img src="data:image/png;base64,' . base64_encode(file_get_contents($tempFile)) . '">';
  3755.                                                   $html .= '</div>';
  3756.                                                   
  3757.                                                    $count++;
  3758.                                         
  3759.                                                    // Fechar a div e inserir quebra de página a cada 63 QR Codes
  3760.                                                    if ($count % 48 == 0) {
  3761.                                                        $html .= '</div><div style="page-break-after: always;"></div>';
  3762.                                                    }
  3763.                                                 
  3764.                                             }
  3765.     
  3766.     
  3767.                                             $caixas->setNome('Caixa '.$nome_caixa_parti);
  3768.                                             $caixas->addCliente($cliente);
  3769.                                             $caixas->setFluxo($fluxo);
  3770.                                             $entityManager->persist($caixas);
  3771.                                             $entityManager->flush();
  3772.                                             $nome_caixa_parti++;
  3773.                                             
  3774.     
  3775.                                         }
  3776.     
  3777.                                         if ($ged == "ok" and $log =="ok") {
  3778.                                     
  3779.                                              // Fechar qualquer div aberta sem completar 63 itens
  3780.                                              if ($count % 48 != 0) {
  3781.                                                 $html .= '</div>';
  3782.                                             }
  3783.                                             
  3784.                                             $html .= '</div></body></html>';
  3785.                                     
  3786.                                             // Carregar o HTML e gerar o PDF
  3787.                                             $dompdf->loadHtml($html);
  3788.                                             $dompdf->setPaper([0, 0, 210, 297], 'portrait'); // Configurar o tamanho de página para A4
  3789.                                             $dompdf->render();
  3790.                                             #file_put_contents('sample1.pdf', $dompdf->output());
  3791.                                             $dompdf->stream('dompdf', array('Attachment' => 0));
  3792.                                         }    
  3793.     
  3794.                                         $registro = new Registro();
  3795.                                         $registro->setOperacao('RECEBIMENTO DE '.$qtd_nome_caixa. ' CAIXA(S)'); 
  3796.                                         $registro->setUser($user_nome);
  3797.                                         $registro->setCliente($cliente_nome);
  3798.                                         $registro->setIp($ip_cliente);
  3799.                                         $entityManager->persist($registro);
  3800.                                         $entityManager->flush();
  3801.                                         
  3802.                                         $etapa->setUpdatedAt($date_hoje);
  3803.                                         $etapa->setRegistro($registro);
  3804.                                         $entityManager->flush();
  3805.     
  3806.                                         $erro = 'ok';
  3807.                                         $p = "Recbimento com sucesso";
  3808.                                         
  3809.                                     }
  3810.     
  3811.                                 }
  3812.     
  3813.     
  3814.     
  3815.                                 if ($ged != "ok" and $log =="ok") {
  3816.                                     
  3817.                                     $qtd_caixa_ = $_POST["qtd_caixa"];
  3818.                                     $options = new Options();
  3819.                                     $options->set('isHtml5ParserEnabled', true);
  3820.                                     $options->set('isPhpEnabled', true);
  3821.                                     $dompdf = new Dompdf($options);
  3822.                             
  3823.                                         $html = '
  3824.                                         <html>
  3825.                                             <head>
  3826.                                                 <style>
  3827.                                                     @page {
  3828.                                                         margin: 35px 18.9px 0px 18.9px;
  3829.                                                         size: 210mm 297mm; /* Ajuste de tamanho do papel */
  3830.                                                     }
  3831.                             
  3832.                                                     body {
  3833.                                                         margin: 0;
  3834.                                                         padding: 0;
  3835.                                                     }
  3836.                                                     
  3837.                                                     .qr-item {
  3838.                                                         border: 2px dotted #000;
  3839.                                                         text-align: center;
  3840.                                                         width: 27.5mm;
  3841.                                                         height: 30.5mm; 
  3842.                                                         display: inline-block;
  3843.                                                     }
  3844.                             
  3845.                                                     .qr-item img {
  3846.                                                         width: 105px; 
  3847.                                                         height: 100px;
  3848.                                                     }
  3849.                             
  3850.                                                     .qr-title {
  3851.                                                         font-size: 16px;
  3852.                                                         font-weight: bold;
  3853.                                                     }
  3854.                             
  3855.                                                     .leo {
  3856.                                                         display: flex;
  3857.                                                         flex-wrap: wrap;
  3858.                                                     }
  3859.                                                 </style>
  3860.                                             </head>
  3861.                                             <body> 
  3862.                                                 <div class="leo">    
  3863.                                         ';
  3864.     
  3865.     
  3866.     
  3867.                                     for ($i=0; $i < $qtd_caixa_; $i++) { 
  3868.                                             
  3869.                                                 $id_cx_ultimo ++;
  3870.                                                 // Gerar QR Code com imagem no centro
  3871.                                             $result = Builder::create()
  3872.                                                 ->writer(new PngWriter())
  3873.                                                 ->writerOptions([])
  3874.                                                 ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  3875.                                                 ->encoding(new Encoding('UTF-8'))
  3876.                                                 ->size(300)
  3877.                                                 ->margin(10)
  3878.                                                 ->logoPath(__DIR__ . '/logo.png') // Caminho do logo central
  3879.                                                 ->build();
  3880.                                                 // Salvar QR Code como arquivo temporário
  3881.                                                 $tempFile = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  3882.                                                 $result->saveToFile($tempFile);
  3883.                                 
  3884.                                                 // Adicionar QR Code ao HTML
  3885.                                                 $html .= '<div class="qr-item">';
  3886.                                                 $html .= '<div class="qr-title">' . $id_cx_ultimo . '</div>';
  3887.                                                 $html .= '<img src="data:image/png;base64,' . base64_encode(file_get_contents($tempFile)) . '">';
  3888.                                                 $html .= '</div>';
  3889.                                     }
  3890.                                     
  3891.                                     $html .= '</div></body></html>';
  3892.                             
  3893.                                     // Carregar o HTML e gerar o PDF
  3894.                                     $dompdf->loadHtml($html);
  3895.                                     $dompdf->setPaper([0, 0, 210, 297], 'portrait'); // Configurar o tamanho de página para A4
  3896.                                     $dompdf->render();
  3897.                                     file_put_contents('sample1.pdf', $dompdf->output());
  3898.                                     $dompdf->stream('dompdf', array('Attachment' => 1));
  3899.     
  3900.     
  3901.                                     $registro = new Registro();
  3902.                                     $registro->setOperacao('RECEBIMENTO DE '.$qtd_caixa_. ' CAIXA(S)'); 
  3903.                                     $registro->setUser($user_nome);
  3904.                                     $registro->setCliente($cliente_nome);
  3905.                                     $registro->setIp($ip_cliente);
  3906.                                     $entityManager->persist($registro);
  3907.                                     $entityManager->flush();
  3908.                                     
  3909.                                     $etapa->setUpdatedAt($date_hoje);
  3910.                                     $etapa->setRegistro($registro);
  3911.                                     $entityManager->flush();
  3912.     
  3913.                                     $erro = 'ok';
  3914.                                     $p = "Recbimento com sucesso";
  3915.     
  3916.     
  3917.                                 }
  3918.     
  3919.     
  3920.     
  3921.     
  3922.                             } else {
  3923.     
  3924.                             echo "<script>alert('ERROR , Selecione a Identificação!');</script>";
  3925.                         }
  3926.                          
  3927.                     }else {
  3928.                         echo "<script>alert('ERROR , Selecione a Quantidade!');</script>";
  3929.                     }
  3930.                }
  3931.                
  3932.                 if($tp =='doc'){
  3933.                     if(isset($_POST["check_cx_e"])){
  3934.                         $yz = "yes";
  3935.                         $checkBoxes = $request->request->all('inputs_cx_e');
  3936.                         $xy = 0;
  3937.                         $qtd_caixas=0;
  3938.                         
  3939.       
  3940.                         foreach ($checkBoxes as $id => $nome) {
  3941.                             $cx_ = $doctrine->getRepository(Cx::class)->find($id);
  3942.                             $_nome =  $cx_->getNome();
  3943.                            
  3944.                             if ($nome =="") {
  3945.                                
  3946.                                 echo "<script>alert('ERROR, Digite no campo gerado acima da tabela qual será repositorio do  ID: $_nome!');</script>";
  3947.                             }
  3948.                             if ($nome != "" ) {
  3949.                                 $id_cx_ultimo = $_nome ;
  3950.                                 $qtd_caixas++;
  3951.                                 $xy = 1;
  3952.                                 $caixas = new Caixa();
  3953.                                 $caixas->setNome($nome);
  3954.                                 $caixas->addCliente($cliente);
  3955.                                 $caixas->setFluxo($fluxo);
  3956.                                 $caixas->setCx($cx_);
  3957.                                 $entityManager->persist($caixas);
  3958.                                 $entityManager->flush();
  3959.                                 $registro = new Registro();
  3960.                                 $registro->setOperacao('RECEBIMENTO DA ID EXISTENTE '.$_nome); 
  3961.                                 $registro->setUser($user_nome);
  3962.                                 $registro->setCliente($cliente_nome);
  3963.                                 $registro->setIp($ip_cliente);
  3964.                                 $entityManager->persist($registro);
  3965.                                 $entityManager->flush();
  3966.                                 
  3967.                                 
  3968.                                 
  3969.                             }
  3970.                             
  3971.                         }
  3972.                        
  3973.                         if($xy==1){
  3974.                             $etapa->setRegistro($registro);
  3975.                             $etapa->setObs($_POST["obs_caixa"]);
  3976.                             $etapa->setUpdatedAt($date_hoje);
  3977.                             $entityManager->flush();
  3978.                             
  3979.                             $registro = new Registro();
  3980.                             $registro->setOperacao('RECEBIMENTO DE  '.$qtd_caixas. ' CAIXA(S) '); 
  3981.                             $registro->setUser($user_nome);
  3982.                             $registro->setCliente($cliente_nome);
  3983.                             $registro->setIp($ip_cliente);
  3984.                             $entityManager->persist($registro);
  3985.                             $entityManager->flush();
  3986.                             $erro = 'ok';
  3987.                             $p = "Recbimento com sucesso";
  3988.                         }
  3989.                       
  3990.                     }else{
  3991.                         $zy = "not";
  3992.                     }
  3993.                     if(isset($_POST["check_caixa_e"])){
  3994.                         $zy = "yes";
  3995.                         $options = new Options();
  3996.                         $options->set('isHtml5ParserEnabled', true);
  3997.                         $options->set('debugKeepTemp', true);
  3998.                         $options->set('isPhpEnabled', true);
  3999.                         $dompdf = new Dompdf($options);
  4000.                         
  4001.                         $html = '
  4002.                                     <html>
  4003.                                         <head>
  4004.                                             <style>
  4005.                                                 @page {
  4006.                                                     margin: 35px 18.9px 0px 18.9px;
  4007.                                                     size: 210mm 297mm; /* Ajuste de tamanho do papel */
  4008.                                                 }
  4009.                         
  4010.                                                 body {
  4011.                                                     margin: 0;
  4012.                                                     padding: 0;
  4013.                                                 }
  4014.                                                 
  4015.                                                 .qr-item {
  4016.                                                     border: 2px dotted #000;
  4017.                                                     text-align: center;
  4018.                                                     width: 32.27mm;
  4019.                                                     height: 34.9mm; 
  4020.                                                     display: inline-block;
  4021.                                                 }
  4022.                                     
  4023.                                                 .qr-item img {
  4024.                                                     width: 115px; 
  4025.                                                     height: 112px;
  4026.                                                 }
  4027.                         
  4028.                                                 .qr-title {
  4029.                                                     font-size: 16px;
  4030.                                                     font-weight: bold;
  4031.                                                 }
  4032.                         
  4033.                                                 .leo {
  4034.                                                     display: flex;
  4035.                                                     flex-wrap: wrap;
  4036.                                                 }
  4037.                                             </style>
  4038.                                         </head>
  4039.                                         <body> 
  4040.                                     
  4041.                                     ';
  4042.                         
  4043.                         $ckeck = $_POST["caixa_e"];
  4044.                         $xy = 0;
  4045.                         $qtd_caixas=0;
  4046.                 
  4047.                         foreach ($ckeck as $key) {
  4048.                             $nome_k = NULL;
  4049.                             $caixa_k = $doctrine->getRepository(Caixa::class)->find($key);
  4050.                             if($caixa_k != NULL ){
  4051.                                 $nome_k = $caixa_k->getNome();
  4052.                             }
  4053.                             
  4054.                             if ($clienteAll_id != 18) {
  4055.                             
  4056.                                 $cx = new Cx();
  4057.                                 $id_cx_ultimo ++;
  4058.                                 $cx->setNome($id_cx_ultimo);
  4059.                                 $cx->setStatus(2);
  4060.                                 $cx->setTexto($nome_k);
  4061.                                 $cx->setImage('ArquivosGED');
  4062.                                 $cx->setCliente($clienteAll);
  4063.                                 $entityManager->persist($cx);
  4064.                                 $entityManager->flush();
  4065.                                 $caixa_k->setCx($cx);
  4066.                                 
  4067.                             }
  4068.                             
  4069.                             $caixa_k->setFluxo($fluxo);
  4070.                             $entityManager->flush();
  4071.                             $registro = new Registro();
  4072.                             $registro->setOperacao('RECEBIMENTO DA CAIXA EXISTENTE '.$nome_k); 
  4073.                             $registro->setUser($user_nome);
  4074.                             $registro->setCliente($cliente_nome);
  4075.                             $registro->setIp($ip_cliente);
  4076.                             $entityManager->persist($registro);
  4077.                             $entityManager->flush();
  4078.                             // Gerar QR Code com imagem no centro
  4079.                             $result = Builder::create()
  4080.                              ->writer(new PngWriter())
  4081.                              ->writerOptions([])
  4082.                              ->data('https://logistica.arquivosdoc.com.br/'.$clienteAll_id.'/'.$id_cx_ultimo)
  4083.                              ->encoding(new Encoding('UTF-8'))
  4084.                              ->size(500)
  4085.                              ->margin(5)
  4086.                              ->logoPath(__DIR__ . '/logo.png') // Caminho do logo central
  4087.                              ->build();
  4088.                              // Salvar QR Code como arquivo temporário
  4089.                              $tempFile = tempnam(sys_get_temp_dir(), 'qr_') . '.png';
  4090.                              $result->saveToFile($tempFile);
  4091.                              
  4092.                              // Adicionar QR Code ao HTML
  4093.                              if ($count % 48 == 0) {
  4094.                                  $html .= '<div class="leo">';
  4095.                              }
  4096.              
  4097.                              // Adicionar QR Code ao HTML
  4098.                              $html .= '<div class="qr-item">';
  4099.                              $html .= '<div class="qr-title">' . $id_cx_ultimo . '</div>';
  4100.                              $html .= '<img src="data:image/png;base64,' . base64_encode(file_get_contents($tempFile)) . '">';
  4101.                              $html .= '</div>';
  4102.                              
  4103.                              
  4104.                              $count++;
  4105.                             // Fechar a div e inserir quebra de página a cada 63 QR Codes
  4106.                             if ($count % 48 == 0) {
  4107.                                 $html .= '</div><div style="page-break-after: always;"></div>';
  4108.                             }
  4109.                              
  4110.                             
  4111.                         }
  4112.                         // Fechar qualquer div aberta sem completar 63 itens
  4113.                         if ($count % 48 != 0) {
  4114.                             $html .= '</div>';
  4115.                         }
  4116.                          
  4117.                         $html .= '</div></body></html>';
  4118.                         
  4119.                         if ($clienteAll_id != 18) {  
  4120.                             // Carregar o HTML e gerar o PDF
  4121.                             $dompdf->loadHtml($html);
  4122.                             $dompdf->setPaper([0, 0, 210, 297], 'portrait'); // Configurar o tamanho de página para A4
  4123.                             $dompdf->render();
  4124.                             #file_put_contents('sample1.pdf', $dompdf->output());
  4125.                             $dompdf->stream('dompdf', array('Attachment' => 0));
  4126.                         }
  4127.                         if($xy==1){
  4128.                             $etapa->setRegistro($registro);
  4129.                             $etapa->setUpdatedAt($date_hoje);
  4130.                             $etapa->setObs($_POST["obs_caixa"]);
  4131.                             $entityManager->flush();
  4132.                             
  4133.                             $registro = new Registro();
  4134.                             $registro->setOperacao('RECEBIMENTO DE  '.$qtd_caixas. ' CAIXA(S) '); 
  4135.                             $registro->setUser($user_nome);
  4136.                             $registro->setCliente($cliente_nome);
  4137.                             $registro->setIp($ip_cliente);
  4138.                             $entityManager->persist($registro);
  4139.                             $entityManager->flush();
  4140.                             $erro = 'ok';
  4141.                             $p = "Recbimento com sucesso";
  4142.                         }
  4143.                       
  4144.                     }else{
  4145.                         $yz = "not";
  4146.                     }
  4147.                     if ($yz == "not" and $zy="not") {
  4148.                         echo "<script>alert('ERROR , Preencha corretamente o formulario, está sem valor , selecione todas as opções necessaria!');</script>";
  4149.                     }
  4150.                    
  4151.                 }
  4152.                
  4153.                
  4154.                
  4155.                
  4156.             }else {
  4157.                 echo "<script>alert('ERROR , Selecione o tipo!');</script>";
  4158.             }
  4159.             
  4160.         }
  4161.         return $this->render('index/recebimento.html.twig', [
  4162.     
  4163.             
  4164.             'p'=>$p,
  4165.             'erro'=>$erro,
  4166.             'pagina' => $pagina,
  4167.             'etapa'=>$etapa,
  4168.             'caixas_setor' => $caixas_setor,
  4169.             'cx_setor' => $cx_setor
  4170.             
  4171.             
  4172.         ]);
  4173.     }
  4174.     #[Route('/index/higienizacao/{id}', name: 'higienizacao')]
  4175.     public function higienizacao( PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer,$id): Response
  4176.     {
  4177.         $user_logado = $this->getUser();
  4178.         $user_nome = $user_logado->getNome();
  4179.         $date_hoje = new \DateTimeImmutable('America/Sao_Paulo');
  4180.         $ip_cliente = $_SERVER['REMOTE_ADDR'];
  4181.         $erro = '';
  4182.         $pagina = 'home';
  4183.         $p ='';
  4184.         $a = 0 ;
  4185.         $clienteAll = null;
  4186.         $cx = null;
  4187.         $caixa = null; 
  4188.         $etapa = $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  4189.         $fluxo = $etapa->getFluxo();
  4190.         $etapa_caixas = $etapa->getCaixa()->toArray();
  4191.         $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo->getId());
  4192.        
  4193.         $e = 0;
  4194.         $f = 0;
  4195.         $clienteId = $session->get('cliente_id');
  4196.         if($clienteId == null){
  4197.             
  4198.             return $this->redirectToRoute('home');
  4199.         }
  4200.         
  4201.         
  4202.         foreach ($etapa_caixas as $key) {
  4203.             $e++;
  4204.         }
  4205.         foreach ($fluxo_caixas as $key) {
  4206.             $f++;
  4207.         }
  4208.         if(isset($_POST["a"])){
  4209.             $a = 2;
  4210.         }
  4211.         
  4212.         $qrCodeData = $request->request->get('qrcode');
  4213.         if(isset($_POST["id_caixas"])){
  4214.             $a = 1 ;
  4215.             $caixa = $doctrine->getRepository(Caixa::class)->findBy(['id' => $_POST["id_caixas"]]);
  4216.             
  4217.             foreach ($caixa as $key) { $caixa_cx_id = $key->getClientes()->toArray();}
  4218.             
  4219.             $cx =  $caixa_cx_id ;
  4220.             
  4221.             foreach ($cx as $key) {$cliente_cx_id = $key->getClienteAll()->getId();}
  4222.             
  4223.             $clienteAll = $doctrine->getRepository(ClienteAll::class)->findClienteWithRelations($cliente_cx_id);
  4224.            
  4225.             
  4226.         }
  4227.         if($qrCodeData != null){
  4228.             
  4229.             $url = $qrCodeData;
  4230.             preg_match('/(\d+)\/(\d+)$/', $url, $matches);
  4231.             if (!empty($matches)) {
  4232.                 $numero1 = $matches[1]; 
  4233.                 $numero2 = $matches[2];
  4234.                 $clienteAll = $doctrine->getRepository(ClienteAll::class)->find($numero1);
  4235.                 $cx = $doctrine->getRepository(Cx::class)->findBy(['nome' => $numero2]);
  4236.                 
  4237.                 foreach ($cx as $key) {
  4238.                     $cx_id = $key->getId();
  4239.                 }
  4240.                     
  4241.                 
  4242.                 $caixa = $doctrine->getRepository(Caixa::class)->findBy(['cx' => $cx_id ]);
  4243.                 $a = 1 ;
  4244.                 
  4245.             } else {
  4246.                 
  4247.               
  4248.             }
  4249.             
  4250.         }
  4251.         if(isset($_POST["cx"])){
  4252.             $clienteAll = $doctrine->getRepository(ClienteAll::class)->findClienteWithRelations($_POST["clienteAll"]);
  4253.             $clienteAll_nome = $clienteAll->getNome();
  4254.             
  4255.             $cx = $doctrine->getRepository(Cx::class)->find($_POST["cx"]);
  4256.             $caixa = $doctrine->getRepository(Caixa::class)->find($_POST["caixas"]);
  4257.             $cliente = $doctrine->getRepository(Cliente::class)->find($_POST["cliente"]);
  4258.             
  4259.             if ($cx != null) {
  4260.                 $cx_nome = 'ID: '.$cx->getNome();
  4261.             }else{
  4262.                 $cx_nome = 'GED: '.$caixa->getNome();
  4263.             }
  4264.         
  4265.             $cliente_nome = $clienteAll_nome;
  4266.             if ($cliente_nome == NULL){
  4267.                 $cliente_nome = $cliente->getNome();
  4268.             }
  4269.             
  4270.             
  4271.             $registro = new Registro();
  4272.             $registro->setOperacao('HIGIENIZAÇÃO '.$cx_nome); 
  4273.             $registro->setUser($user_nome);
  4274.             $registro->setCliente($cliente_nome);
  4275.             $registro->setIp($ip_cliente);
  4276.             $entityManager->persist($registro);
  4277.             $entityManager->flush();
  4278.             
  4279.             if($cx != null){
  4280.                 
  4281.                 $etapa->addCx($cx);
  4282.             }
  4283.             
  4284.             $etapa->addCaixa($caixa);
  4285.             $caixa->setHigienizaAt($date_hoje);
  4286.             $e++;
  4287.             if ($e == $f) {
  4288.                 
  4289.                 $registro = new Registro();
  4290.                 $registro->setOperacao('HIGIENIZAÇÃO DE '.$f. ' CAIXA(S)'); 
  4291.                 $registro->setUser('CONCLUIDO PELA EQUIPE');
  4292.                 $registro->setCliente($cliente_nome);
  4293.                 $registro->setIp($ip_cliente);
  4294.                 $entityManager->persist($registro);
  4295.                 $entityManager->flush();
  4296.                 $etapa->setRegistro($registro);
  4297.                 $etapa->setUpdatedAt($date_hoje);
  4298.                 $entityManager->flush();
  4299.             }
  4300.             
  4301.             $entityManager->flush();
  4302.             $erro = 'ok';
  4303.             $p = "Etapa concluída com sucesso";
  4304.         }
  4305.         
  4306.         return $this->render('index/higienizacao.html.twig', [
  4307.     
  4308.             'id'=>$id,
  4309.             'p'=>$p,
  4310.             'erro'=>$erro,
  4311.             'pagina' => $pagina,
  4312.             'a'=>$a,
  4313.             'clienteAll' => $clienteAll,
  4314.             'cx' =>$cx ,
  4315.             'caixa' => $caixa,
  4316.             'fluxo_caixas'=>$fluxo_caixas
  4317.             
  4318.             
  4319.             
  4320.         ]);
  4321.     }
  4322.    
  4323.     #[Route('/index/digitalizacao/{id}', name: 'digitalizacao')]
  4324.     public function digitalizacao(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session,MessageBusInterface $bus,$id): Response
  4325.     {
  4326.         $ip_cliente = $_SERVER['REMOTE_ADDR'];
  4327.         $etapa = $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  4328.         $fluxo = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($etapa->getFluxo()->getId());
  4329.         $cliente_nome = $fluxo->getCliente()->getNome();
  4330.         $cliente_id = $fluxo->getCliente();
  4331.         $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo->getId());
  4332.         $form = $this->createForm(UploadType::class);
  4333.         $user_logado = $this->getUser();
  4334.         $user_logado_id = $user_logado->getId();
  4335.         $userId = $user_logado_id;
  4336.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  4337.         $form->handleRequest($request);
  4338.         $dotenv = new Dotenv();
  4339.         $dotenv->load(__DIR__.'/.env');
  4340.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  4341.         $hoje_formt=$hoje->format('Y-m-d') ;
  4342.         $dia_prod = 'de hoje';
  4343.         $erro = '';
  4344.         $ii=0;
  4345.         $pagina = 'export';
  4346.         $p = '';
  4347.         $uuid = Uuid::v4();
  4348.         $user = $this->getUser();
  4349.         $user_nome= $user->getEmail();
  4350.         $user_nome_name= $user->getNome();
  4351.         $pasta_user=$user_nome.'/';
  4352.         $cliente_alls = "";
  4353.         $arr = [];
  4354.         $arrr=0;
  4355.         $f = 0;
  4356.         $dt = '';
  4357.         $clientS3 = new  S3Client([
  4358.             'region'  => 'sa-east-1',
  4359.             'version' => 'latest',
  4360.             'credentials' => [ 
  4361.                 'key'    => $_ENV['AWS_KEY'],
  4362.                 'secret' => $_ENV['AWS_SECRET'],
  4363.             ],
  4364.         
  4365.         ]);
  4366.         foreach ($fluxo_caixas as $key) {
  4367.             $f++;
  4368.         }
  4369.         if(isset($_POST["btn_cliente"])){
  4370.             
  4371.             $session->set('cliente_id', $_POST["btn_cliente"]);
  4372.             return $this->redirectToRoute('home');
  4373.         }
  4374.        
  4375.             
  4376.             
  4377.        
  4378.         $clienteId = $session->get('cliente_id');
  4379.         
  4380.         if ($clienteId == null ) {
  4381.             
  4382.             $caixas =  "";
  4383.             $cliente_session = "";
  4384.             return $this->redirectToRoute('home');
  4385.        
  4386.         } else {
  4387.             
  4388.             $caixas = $fluxo_caixas;
  4389.             $cliente_session =  $doctrine->getRepository(Cliente::class)->find($clienteId);       
  4390.         }
  4391.         
  4392.         
  4393.         if(isset($_POST["botao_export"]))
  4394.         {
  4395.             
  4396.             $caixaId = $_POST["caixas"];
  4397.             
  4398.             $caixa_id = $doctrine->getRepository(Caixa::class)->find($_POST["caixas"]);
  4399.             $clientes= $cliente_id->getId();
  4400.             $cliente_alls = $cliente_id->getClienteAll()->getId();
  4401.             $clienteId=$clientes;
  4402.             $clientes_status= $cliente_id->getExtraFields();
  4403.             if(!$clientes_status){
  4404.                 $clientes_status="ged";
  4405.             }
  4406.             $conteiner = $_POST["conteiner"];
  4407.             $cont_file = 0 ;
  4408.             $umlautString =$cliente_nome;
  4409.             $slugger = new AsciiSlugger();
  4410.             $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  4411.             $caminho = strtolower ($teste.'/');
  4412.                     
  4413.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  4414.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  4415.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  4416.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  4417.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  4418.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  4419.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  4420.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  4421.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  4422.             if($clientes ==  40){$caminho='fasf-atas-e-diario/';}
  4423.             if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  4424.            
  4425.             $filesTmp  = $_FILES['file']['tmp_name'];
  4426.             $filesName = $_FILES['file']['name'];
  4427.             
  4428.             foreach ($filesTmp as $index => $file) {
  4429.             
  4430.                 $uuid = Uuid::v4();
  4431.                 $cont_file++;
  4432.                 // nome original do arquivo
  4433.                 $originalName = pathinfo($filesName[$index], PATHINFO_FILENAME);
  4434.                 // sanitiza o nome (remove acentos, espaços estranhos etc.)
  4435.                 $slugger = new AsciiSlugger();
  4436.                 $safeName = strtolower($slugger->slug($originalName)->toString());
  4437.             
  4438.                 // 🔹 Se cliente for local, usa nome original
  4439.                 if ($clientes_status === 'local') {
  4440.             
  4441.             
  4442.                     $filename = $safeName . '.pdf';
  4443.             
  4444.                 } else {
  4445.                     // padrão: UUID
  4446.                     $filename = $uuid . '.pdf';
  4447.                 }
  4448.             
  4449.                 $tempDir = __DIR__ . '/../../var/uploads/messenger';
  4450.                 if (!is_dir($tempDir)) {
  4451.                     mkdir($tempDir, 0777, true);
  4452.                 }
  4453.             
  4454.                 $tempFilePath = $tempDir . '/' . $filename;
  4455.             
  4456.                 move_uploaded_file($file, $tempFilePath);
  4457.                 #chmod($tempFilePath, 0644);
  4458.                 if (!file_exists($tempFilePath) || filesize($tempFilePath) === 0) {
  4459.                     throw new \RuntimeException(
  4460.                         'Falha ao gravar PDF temporário: ' . $tempFilePath
  4461.                     );
  4462.                 }
  4463.                 
  4464.                 // evita race condition de filesystem
  4465.                 clearstatcache(true, $tempFilePath);
  4466.             
  4467.                 $bus->dispatch(new UploadMultipartMessage(
  4468.                     $tempFilePath,
  4469.                     $filename,
  4470.                     $caminho,
  4471.                     '',
  4472.                     $caixaId,
  4473.                     $clienteId,
  4474.                     $userId,
  4475.                     0,
  4476.                     $conteiner,
  4477.                     $clientes,
  4478.                     $clientes_status,
  4479.                     $safeName,
  4480.                     $originalName,
  4481.                     $cliente_alls 
  4482.                 ));
  4483.             }
  4484.            
  4485.             $log = new Registro();
  4486.             $log->setOperacao('EXPORTOU '.$cont_file.' DOCUMENTO(S)'); 
  4487.             $log->setUser($user_nome_name);
  4488.             $log->setCliente($cliente_nome);
  4489.             $entityManager->persist($log);
  4490.             $entityManager->flush();
  4491.             
  4492.             return $this->redirectToRoute('digitalizacao', ['id' => $id]);
  4493.             
  4494.         
  4495.         }
  4496.         if(isset($_POST["caixa_total"])){
  4497.             $caixa_total = $_POST["caixa_total"];
  4498.             $documento_total =$_POST["documento_total"];
  4499.             $qtd_total =$_POST["qtd_total"];
  4500.                 $registro = new Registro();
  4501.                 $registro->setOperacao('DIGITALIZAÇÃO:  '.$caixa_total. ' CAIXA(S) / '.$documento_total.' DOCUMENTO(S) / '.$qtd_total.' IMAGEN(S)'); 
  4502.                 $registro->setUser('CONCLUIDO PELA EQUIPE');
  4503.                 $registro->setCliente($cliente_nome);
  4504.                 $registro->setIp($ip_cliente);
  4505.                 $entityManager->persist($registro);
  4506.                 $entityManager->flush();
  4507.                 $etapa->setRegistro($registro);
  4508.                 $etapa->setUpdatedAt($hoje);
  4509.                 $entityManager->flush();
  4510.                 $erro = 'ok';
  4511.                 $p = "Etapa concluída com sucesso";
  4512.         }
  4513.        
  4514.         return $this->render('index/digitalizacao.html.twig', [
  4515.             'id'=>$id,
  4516.             'p'=>$p,
  4517.             'erro'=>$erro,
  4518.             'pagina' => $pagina,
  4519.             'caixas' => $caixas,
  4520.             'user_logado' => $user_logado,
  4521.             'cliente' => $cliente,
  4522.             'cliente_session' => $cliente_session,
  4523.             'form' => $form->createView(),
  4524.             'dia_prod' => $dia_prod,
  4525.             'fluxo' => $fluxo
  4526.         ]);
  4527.     }
  4528.     #[Route('/index/indexacao/{id}', name: 'indexacao')]
  4529.     public function indexacao(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager , SessionInterface $session,$id): Response
  4530.     {   
  4531.         
  4532.         $clientS3 = new  S3Client([
  4533.                     'region'  => 'sa-east-1',
  4534.                     'version' => 'latest',
  4535.                     'credentials' => [ 
  4536.                         'key'    => $_ENV['AWS_KEY'],
  4537.                         'secret' => $_ENV['AWS_SECRET'],
  4538.                     ],
  4539.                 ]);
  4540.         $ip_cliente = $_SERVER['REMOTE_ADDR'];
  4541.         $etapa = $doctrine->getRepository(Etapa::class)->findWithAllRelations($id);
  4542.         $fluxo = $doctrine->getRepository(Fluxo::class)->findWithAllRelations($etapa->getFluxo()->getId());
  4543.         $cliente_nome = $fluxo->getCliente()->getNome();
  4544.         $cliente_etapa = $fluxo->getCliente();
  4545.         $fluxo_caixas = $doctrine->getRepository(Caixa::class)->findByFluxoWithRelations($fluxo->getId());
  4546.         $caixaIds = array_map(fn($caixa) => $caixa->getId(), $fluxo_caixas);
  4547.         $documentoRepository = $entityManager->getRepository(Documento::class);
  4548.         $pagina = 1;
  4549.         $limite = 100;
  4550.         $offset = ($pagina - 1) * $limite;
  4551.         $total = $documentoRepository->createQueryBuilder('d')
  4552.             ->select('COUNT(d.id)')
  4553.             ->where('IDENTITY(d.caixa) IN (:caixas)')
  4554.             ->andWhere('d.tipo IS NULL')
  4555.             ->setParameter('caixas', $fluxo_caixas)
  4556.             ->getQuery()
  4557.             ->getSingleScalarResult();
  4558.         $documentos = $documentoRepository->createQueryBuilder('d')
  4559.             ->where('IDENTITY(d.caixa) IN (:caixas)')
  4560.             ->andWhere('d.tipo IS NULL')
  4561.             ->setParameter('caixas', $caixaIds)
  4562.             ->orderBy('d.createdAt', 'ASC')
  4563.             ->setFirstResult($offset)
  4564.             ->setMaxResults($limite)
  4565.             ->getQuery()
  4566.             ->getResult();
  4567.         
  4568.         
  4569.             // Executa a query
  4570.         $caixas = $fluxo_caixas;
  4571.         $user_logado = $this->getUser();
  4572.         $form = $this->createForm(UploadType::class);
  4573.         $form->handleRequest($request);
  4574.         $user_logado_tipoAcesso = $user_logado->getTipoAcesso();
  4575.         $user_logado_nome = $user_logado->getNome();
  4576.         $user_logado_id = $user_logado->getId();
  4577.         $cliente =  $doctrine->getRepository(User::class)->findClientsByUserId($user_logado_id);
  4578.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  4579.         $hoje_formt=$hoje->format('Y-m-d');
  4580.         $doc = $entityManager->getRepository(Documento::class)->findByUserIndexAndDate($user_logado_nome, $hoje_formt);
  4581.         $dia_prod = 'de hoje';
  4582.         $permissao = [];
  4583.         $list_indexador = [];
  4584.         $index_all =  $doctrine->getRepository(Tipo::class)->findBy(['cliente' => $cliente_etapa]);
  4585.         $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $cliente_etapa]);
  4586.         $cliente_ids =$cliente_etapa ;
  4587.         
  4588.        
  4589.             
  4590.         $cliente_nome= $cliente_ids->getNome();
  4591.         $clientes= $cliente_ids->getId();
  4592.         $umlautString =$cliente_nome;
  4593.         $slugger = new AsciiSlugger();
  4594.         $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  4595.         $caminho = strtolower ($teste.'/');
  4596.                         
  4597.         if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  4598.         if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  4599.         if($clientes == 35){$caminho='pmecj-sp-saude/';}
  4600.         if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  4601.         if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  4602.         if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  4603.         if($clientes ==  15){$caminho='cbsi-dossies/';}
  4604.         if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  4605.         if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  4606.         if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  4607.       
  4608.           
  4609.         if(isset($_POST["btn_cliente"])){
  4610.             
  4611.             $session->set('cliente_id', $_POST["btn_cliente"]);
  4612.             return $this->redirectToRoute('home');
  4613.         }
  4614.         $clienteId = $session->get('cliente_id');
  4615.         
  4616.         
  4617.         if ($clienteId == null ) {
  4618.             
  4619.             $caixas =  "";
  4620.             $cliente_session = "";
  4621.             return $this->redirectToRoute('home');
  4622.        
  4623.         }
  4624.            
  4625.         $erro = '';
  4626.         $ii=0;
  4627.         $pagina = 'index';
  4628.         $p = '';
  4629.         $link = '';
  4630.         $mx = 0;
  4631.         $xy = 0 ; 
  4632.         $yz = 0 ; 
  4633.         $ay = 0 ;
  4634.         $ky = 0 ;
  4635.         $pdf ='';
  4636.         $pagina_h4 ='Documento(s) para indexar';
  4637.         $nome_menu_ = '';
  4638.         $index_tipo='';
  4639.         $uuid = Uuid::v4();
  4640.         $user = $this->getUser();
  4641.         $user_nome= $user->getEmail();
  4642.         $user_nome_name= $user->getNome();
  4643.         $pasta_user=$user_nome.'/';
  4644.         $arr = [];
  4645.         $arrr=0;
  4646.         $index_find = null;
  4647.         $dt = '';
  4648.         
  4649.         
  4650.      
  4651.             
  4652.        
  4653.         if(isset($_POST["botao_index"])){
  4654.             
  4655.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4656.             $link = $pdf->getImage();
  4657.             $xy = 1 ;
  4658.             
  4659.         }
  4660.         if(isset($_POST["botao_doc"])){
  4661.             
  4662.             
  4663.             $yz = 0 ;
  4664.             $xy = 1 ;
  4665.             $ay = 1 ;
  4666.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4667.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4668.            
  4669.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4670.             $index_tipo_tipo =  $index_tipo->getNome();
  4671.             $link = $pdf->getImage();
  4672.             $fase=$_POST["fase"];
  4673.             $data = $_POST["data"];
  4674.             $cx = $_POST["caixas"];
  4675.             $classifica = $_POST["classifica"];
  4676.             $desc = $_POST["desc"];
  4677.             $assunto = $_POST["assunto"];
  4678.             $chave = $_POST["chave"];
  4679.             $nome = $_POST["nome"];
  4680.             $conteiner = $_POST["conteiner"];
  4681.             
  4682.             
  4683.             $caixa_id = $doctrine->getRepository(Caixa::class)->find($cx);
  4684.             
  4685.             
  4686.             
  4687.             
  4688.             // Exibe os números encontrados
  4689.             
  4690.             if ($clientes != 7) {
  4691.                 preg_match_all('/\d+/', $fase, $matches);
  4692.                 $numeros = array_map('intval', $matches[0]);
  4693.                 if ($data != "") {
  4694.                     if ($numeros != [] ) {
  4695.                         if ($fase != "") {
  4696.         
  4697.                             // Número inteiro que você deseja somar ao ano
  4698.                             $numeroParaSomar = $numeros[0];
  4699.         
  4700.                             // Extrair o ano da data
  4701.                             list($ano, $mes, $dia) = explode('-', $data);
  4702.         
  4703.                             // Converter o ano para um número inteiro
  4704.                             $ano = intval($ano);
  4705.         
  4706.                             // Somar o número ao ano
  4707.                             $data_vecimento =  $ano + $numeroParaSomar.'-'.$mes.'-'. $dia;
  4708.         
  4709.                             $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  4710.         
  4711.                         }
  4712.                 }
  4713.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  4714.                 }
  4715.             }    
  4716.             
  4717.             if ($clientes == 7) {
  4718.                   $pdf->setVencimentoDocumento(new \DateTimeImmutable($fase));
  4719.                   $pdf->setDataDocumento(new \DateTimeImmutable($data));
  4720.              }
  4721.             
  4722.             
  4723.             $pdf->setAssunto($assunto);
  4724.             if ($classifica != "") {
  4725.                 $classifica_id = $doctrine->getRepository(Classificacao::class)->find($classifica);
  4726.                 $pdf->setClassificacao($classifica_id);
  4727.             }
  4728.             $pdf->setCaixa($caixa_id);
  4729.             $pdf->setExtraFields($desc);
  4730.             $pdf->setNome($nome);
  4731.             $pdf->setKeywords($chave);
  4732.             $pdf->setUserIndex($user_nome_name);
  4733.             $pdf->setConteiner($conteiner);
  4734.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  4735.             $pdf->setTipo($index_tipo);
  4736.             $entityManager->flush();
  4737.             $id_pd = $pdf->getId();    
  4738.             $log = new Registro();
  4739.             $log->setOperacao('Indexou o Documento com id '.$id_pd); 
  4740.             $log->setUser($user_nome_name);
  4741.             $log->setCliente($cliente_nome);
  4742.             $entityManager->persist($log);
  4743.             $entityManager->flush();
  4744.             $erro = 'ok';
  4745.             $p =  $index_tipo_tipo.' indexado com sucesso';
  4746.             
  4747.            
  4748.             
  4749.            
  4750.         }   
  4751.         if(isset($_POST["botao_index_edit"])){
  4752.             
  4753.             $yz = 0 ;
  4754.             $xy = 1 ;
  4755.             $ay = 1 ;
  4756.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4757.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4758.             $link = $pdf->getImage();
  4759.         }
  4760.         if(isset($_POST["botao_volta"])){
  4761.             $xy = 0 ;
  4762.             $yz = 0 ;
  4763.         }
  4764.         if(isset($_POST["index_button"])){
  4765.             
  4766.             
  4767.             $yz = 0 ;
  4768.             $xy = 1 ;
  4769.             $ay = 1 ;
  4770.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4771.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["index_button"]);
  4772.             $link = $pdf->getImage();
  4773.         }
  4774.         if(isset($_POST["botao_cancel"])){
  4775.             $yz = 0 ;
  4776.             $xy = 1 ;
  4777.             $ay = 0 ;
  4778.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4779.             $link = $pdf->getImage();
  4780.             
  4781.         }
  4782.         if(isset($_POST["delet"])){
  4783.            
  4784.             $ky = 1 ;
  4785.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["delet"]);
  4786.             $documentos = $doctrine->getRepository(Documento::class)->findBy(['id' => $_POST["delet"]]);
  4787.             
  4788.             if($pdf->getTipo()!= null){
  4789.                 $index_find =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  4790.                 $pagina =$index_find->getTipo();
  4791.                 $pagina_h4 ='Documento(s) do tipo ( '.$index_find->getTipo().' )';
  4792.             }
  4793.                         
  4794.         }
  4795.         if(isset($_POST["delet_cancel"])){
  4796.             $ky = 0 ;
  4797.         }
  4798.         if(isset($_POST["delet_sim"])){
  4799.             
  4800.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  4801.             $id_pd = $pdf->getId();
  4802.             $entityManager->remove($pdf);
  4803.             $entityManager->flush();
  4804.           
  4805.             $log = new Registro();
  4806.             $log->setOperacao('Excluiu Documento com id '.$id_pd); 
  4807.             $log->setUser($user_nome_name);
  4808.             $log->setCliente($cliente_nome);
  4809.             $entityManager->persist($log);
  4810.             $entityManager->flush();
  4811.             $erro = 'ok';
  4812.             $p = 'Documento com id '.$id_pd.' excluido com sucesso '; 
  4813.         }
  4814.         if(isset($_POST["index_edit"])){
  4815.             $yz = 0 ;
  4816.             $xy = 1 ;
  4817.             $ay = 2 ;
  4818.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  4819.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($_POST["id_index"]);
  4820.             $link = $pdf->getImage();
  4821.         }
  4822.        
  4823.         if(isset($_POST["caixa_total"])){
  4824.             $caixa_total = $_POST["caixa_total"];
  4825.             $documento_total =$_POST["documento_total"];
  4826.             $qtd_total =$_POST["qtd_total"];
  4827.                 $registro = new Registro();
  4828.                 $registro->setOperacao('INDEXADO:  '.$caixa_total. ' CAIXA(S) / '.$documento_total.' DOCUMENTO(S) / '); 
  4829.                 $registro->setUser('CONCLUIDO PELA EQUIPE');
  4830.                 $registro->setCliente($cliente_nome);
  4831.                 $registro->setIp($ip_cliente);
  4832.                 $entityManager->persist($registro);
  4833.                 $entityManager->flush();
  4834.                 $etapa->setRegistro($registro);
  4835.                 $etapa->setUpdatedAt($hoje);
  4836.                 $entityManager->flush();
  4837.                 $erro = 'ok';
  4838.                 $p = "Etapa concluída com sucesso";
  4839.         }
  4840.         
  4841.            $cmd = $clientS3->getCommand('GetObject', [
  4842.                 'Bucket' => 'arquivosdoc',
  4843.                 'Key'    => $caminho. $link, 
  4844.             ]);
  4845.             
  4846.             $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  4847.             $all_Url = (string) $req->getUri();
  4848.         
  4849.         return $this->render('index/indexacao.html.twig', [
  4850.             'documentos' => $documentos,
  4851.             'xy' => $xy,
  4852.             'yz' => $yz,
  4853.             'ay'=>$ay,
  4854.             'link' => $link,
  4855.             'pdf'=>$pdf,
  4856.             'p'=>$p,
  4857.             'erro'=>$erro,
  4858.             'index_all'=>$index_all,
  4859.             'index_tipo'=>$index_tipo,
  4860.             'ky'=>$ky,
  4861.             'pagina' => $pagina,
  4862.             'pagina_h4' =>$pagina_h4,
  4863.             'index_find'=>$index_find,
  4864.             'mx'=>$mx,
  4865.             'class'=>$class,
  4866.             'caixas' => $caixas,
  4867.             'permissao'=>$permissao,
  4868.             'doc'=>$doc,
  4869.             'dia_prod' => $dia_prod,
  4870.             'fluxo' => $fluxo,
  4871.             'id' => $id,
  4872.             'caminho' =>$caminho,
  4873.             'clientes'=>$clientes,
  4874.             'all_Url'=>$all_Url,
  4875.             'total'=>$total
  4876.         ]);
  4877.     }
  4878.     
  4879.    
  4880.     
  4881.     #[Route('/fila/count', name: 'fila_count', methods: ['GET'])]
  4882.     public function count(EntityManagerInterface $entityManager): JsonResponse
  4883.     {
  4884.         $userLogado = $this->getUser();
  4885.         $userLogadoId = $userLogado->getId();
  4886.     
  4887.         $repository = $entityManager->getRepository(MessengerMessages::class);
  4888.     
  4889.         $count = $repository->countPendingMessagesByUser($userLogadoId);
  4890.     
  4891.         $messages = $repository->createQueryBuilder('m')
  4892.             ->where('m.delivered_at IS NULL')
  4893.             ->orderBy('m.id', 'ASC')
  4894.             ->getQuery()
  4895.             ->getResult();
  4896.     
  4897.         $fila = [];
  4898.         $usuariosJaProcessados = [];
  4899.         $posicaoUsuario = null;
  4900.     
  4901.         foreach ($messages as $index => $message) {
  4902.     
  4903.             $body = $message->getBody();
  4904.     
  4905.             preg_match('/;i:(\d+);s:8:/', $body, $matches);
  4906.     
  4907.             $userIdFila = $matches[1] ?? null;
  4908.     
  4909.             if (!$userIdFila) {
  4910.                 continue;
  4911.             }
  4912.     
  4913.             // 🔥 evita duplicar usuário na fila
  4914.             if (isset($usuariosJaProcessados[$userIdFila])) {
  4915.                 continue;
  4916.             }
  4917.     
  4918.             $usuariosJaProcessados[$userIdFila] = true;
  4919.     
  4920.             $usuario = $entityManager
  4921.                 ->getRepository(User::class)
  4922.                 ->find($userIdFila);
  4923.     
  4924.             $posicao = count($fila) + 1;
  4925.     
  4926.             $item = [
  4927.                 'posicao' => $posicao,
  4928.                 'user_id' => $userIdFila,
  4929.                 'nome' => $usuario?->getNome(),
  4930.             ];
  4931.     
  4932.             $fila[] = $item;
  4933.     
  4934.             if ((int)$userIdFila === (int)$userLogadoId) {
  4935.                 $posicaoUsuario = $posicao;
  4936.             }
  4937.         }
  4938.     
  4939.         // calcula quantos faltam para o usuário logado
  4940.         $faltam = $posicaoUsuario ? ($posicaoUsuario - 1) : null;
  4941.     
  4942.         return new JsonResponse([
  4943.             'count' => $count,
  4944.             'minha_posicao' => $posicaoUsuario,
  4945.             'faltam' => $faltam,
  4946.             'fila' => $fila,
  4947.         ]);
  4948.     }
  4949.     
  4950.     #[Route('/index/qualidade', name: 'qualidade')]
  4951.     public function qualidade(Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager , SessionInterface $session,DriveToOneDriveService $service): Response
  4952.     {   
  4953.         $clienteId = $session->get('cliente_id');
  4954.         $ip_cliente = $_SERVER['REMOTE_ADDR'];
  4955.         $caixaIds = "LEONARDO DE SOUZA CRUZEIRO";
  4956.         $documentoRepository = $entityManager->getRepository(Documento::class);
  4957.         $query = $documentoRepository->createQueryBuilder('d')
  4958.         ->where('d.user_index = :caixaIds')
  4959.         ->andWhere('d.cliente = :clienteId')
  4960.         ->andWhere('(d.situacao = :situacao OR d.situacao IS NULL)')
  4961.         ->andWhere('d.tipo IS NOT NULL')
  4962.         ->setParameter('situacao', '')
  4963.         ->setParameter('caixaIds', $caixaIds)
  4964.         ->setParameter('clienteId', $clienteId)
  4965.         ->orderBy('d.indexAt', 'ASC')
  4966.         ->setMaxResults(100)
  4967.         ->getQuery();
  4968.         
  4969.         
  4970.         $total = $documentoRepository->createQueryBuilder('d')
  4971.         ->select('COUNT(d.id)')
  4972.         ->where('d.user_index = :caixaIds')
  4973.         ->andWhere('d.cliente = :clienteId')
  4974.         ->andWhere('(d.situacao = :situacao OR d.situacao IS NULL)')
  4975.         ->setParameter('situacao', '')
  4976.         ->setParameter('caixaIds', $caixaIds)
  4977.         ->setParameter('clienteId', $clienteId)
  4978.         ->getQuery()
  4979.         ->getSingleScalarResult();
  4980.        
  4981.         // Executa a query
  4982.         $documentos = $query->getResult();
  4983.         #dd($documentos);
  4984.         $dotenv = new Dotenv();
  4985.         $dotenv->load(__DIR__.'/.env');
  4986.         $user_logado = $this->getUser();
  4987.         $form = $this->createForm(UploadType::class);
  4988.         $form->handleRequest($request);
  4989.         $user_logado_tipoAcesso = $user_logado->getTipoAcesso();
  4990.         $user_nome_name = $user_logado->getNome();
  4991.         $user_logado_id = $user_logado->getId();
  4992.         $hoje = new \DateTimeImmutable('America/Sao_Paulo');
  4993.         $hoje_formt=$hoje->format('Y-m-d');
  4994.         $dia_prod = 'de hoje';
  4995.         $permissao = [];
  4996.         $list_indexador = [];
  4997.         $slugger = new AsciiSlugger();
  4998.         $erro = '';
  4999.         $ii=0;
  5000.         $pagina = 'qualidade';
  5001.         $p = '';
  5002.         $link = '';
  5003.         $xy = 0 ; 
  5004.         $pdf ='';
  5005.         $umlautString = '';
  5006.         $clientes = 0;
  5007.         $caminho ='';
  5008.         $class ="";
  5009.         $all_Url="";
  5010.         
  5011.         $clientS3 = new  S3Client([
  5012.                 'region'  => 'sa-east-1',
  5013.                 'version' => 'latest',
  5014.                 'credentials' => [ 
  5015.                     'key'    => $_ENV['AWS_KEY'],
  5016.                     'secret' => $_ENV['AWS_SECRET'],
  5017.                 ],
  5018.             ]);
  5019.        
  5020.         if(isset($_POST["botao_index"])){
  5021.             
  5022.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id"]);
  5023.             $clientes = $pdf->getCliente()->getId();
  5024.             $clienteRepository = $entityManager->getRepository(Cliente::class);
  5025.             $class =  $doctrine->getRepository(Classificacao::class)->findBy(['cliente' => $clientes]);
  5026.             $query = $clienteRepository->createQueryBuilder('c')
  5027.                 ->where('c.id = :caixaIds')
  5028.                 ->setParameter('caixaIds', $clientes)
  5029.                 ->getQuery();
  5030.             $cl = $query->getSingleResult();
  5031.             $link = $pdf->getImage();
  5032.             $xy = 1 ;
  5033.             $umlautString = $cl->getNome();
  5034.             $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  5035.             $caminho = strtolower ($teste.'/');
  5036.                     
  5037.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  5038.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  5039.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  5040.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  5041.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  5042.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  5043.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  5044.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  5045.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  5046.             if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  5047.             
  5048.             $cmd = $clientS3->getCommand('GetObject', [
  5049.                 'Bucket' => 'arquivosdoc',
  5050.                 'Key'    => $caminho. $link, 
  5051.                 ]);
  5052.                 
  5053.             $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  5054.             $all_Url = (string) $req->getUri();
  5055.                 
  5056.         }
  5057.         if(isset($_POST["botao_doc"])){
  5058.             
  5059.             $yz = 0 ;
  5060.             $xy = 1 ;
  5061.             $ay = 1 ;
  5062.             
  5063.             $pdf =  $doctrine->getRepository(Documento::class)->find($_POST["id_pdf"]);
  5064.             
  5065.             // 1. Capturar valores originais da IA antes da edição do humano
  5066.             $originalAssunto = $pdf->getAssunto();
  5067.             $originalDescricao = $pdf->getExtraFields();
  5068.             $originalNome = $pdf->getNome();
  5069.             $originalKeywords = $pdf->getKeywords();
  5070.             $originalConteiner = $pdf->getConteiner();
  5071.             $originalDataDoc = $pdf->getDataDocumento() ? $pdf->getDataDocumento()->format('Y-m-d') : null;
  5072.             $originalDataVenc = $pdf->getVencimentoDocumento() ? $pdf->getVencimentoDocumento()->format('Y-m-d') : null;
  5073.             $originalClassId = $pdf->getClassificacao() ? $pdf->getClassificacao()->getId() : null;
  5074.             
  5075.             $index_tipo =  $doctrine->getRepository(Tipo::class)->find($pdf->getTipo());
  5076.             $index_tipo_tipo =  $index_tipo->getNome();
  5077.             $link = $pdf->getImage();
  5078.             $data = $_POST["data"];
  5079.             $desc = $_POST["desc"];
  5080.             $assunto = $_POST["assunto"];
  5081.             $chave = $_POST["chave"];
  5082.             $nome = $_POST["nome"];
  5083.             $conteiner = $_POST["conteiner"];
  5084.             $classifica = $_POST["classifica"];
  5085.             $fase = $_POST["fase"];
  5086.             
  5087.             preg_match_all('/\d+/', $fase, $matches);
  5088.             $numeros = array_map('intval', $matches[0]);
  5089.             $novaDataVencVal = null;
  5090.             if ($clientes != 7) {
  5091.                 if ($data != "") {
  5092.                     if ($fase != "") {
  5093.                         $numeroParaSomar = $numeros[0];
  5094.                         list($ano, $mes, $dia) = explode('-', $data);
  5095.                         $ano = intval($ano);
  5096.                         $data_vecimento =  $ano + $numeroParaSomar.'-'.$mes.'-'. $dia;
  5097.                         $novaDataVencVal = $data_vecimento;
  5098.                         $pdf->setVencimentoDocumento(new \DateTimeImmutable($data_vecimento));
  5099.                     }
  5100.                 $pdf->setDataDocumento(new \DateTimeImmutable($data));
  5101.                 }
  5102.             }  
  5103.             $classificaObj = null;
  5104.             if ($classifica != "") {
  5105.                 $classifica_id = $doctrine->getRepository(Classificacao::class)->find($classifica);
  5106.                 $classificaObj = $classifica_id;
  5107.                 $pdf->setClassificacao($classifica_id);
  5108.             }
  5109.             
  5110.             $clienteExtraFields = $entityManager->createQueryBuilder()
  5111.                 ->select('c.extraFields')
  5112.                 ->from(Cliente::class, 'c')
  5113.                 ->where('c.id = :id')
  5114.                 ->setParameter('id', $clienteId)
  5115.                 ->getQuery()
  5116.                 ->getSingleScalarResult();
  5117.             
  5118.             if ($clienteExtraFields == "local") {
  5119.                 $pdf->setRenomear(1);
  5120.             }
  5121.             
  5122.             $pdf->setAssunto($assunto);
  5123.             $pdf->setExtraFields($desc);
  5124.             $pdf->setNome($nome);
  5125.             $pdf->setKeywords($chave);
  5126.             $pdf->setUserIndex($user_nome_name);
  5127.             $pdf->setConteiner($conteiner);
  5128.             // 2. Cálculo da assertividade usando similaridade de strings e verificação de campos
  5129.             $calcularSimilaridade = function(?string $original, ?string $novo): float {
  5130.                 $original = trim($original ?? '');
  5131.                 $novo = trim($novo ?? '');
  5132.                 if ($original === '' && $novo === '') {
  5133.                     return 100.0;
  5134.                 }
  5135.                 
  5136.                 if ($original === '' || $novo === '') {
  5137.                     return 0.0;
  5138.                 }
  5139.                 similar_text($original, $novo, $percentual);
  5140.                 return $percentual; 
  5141.             };
  5142.             $scoreAssunto = $calcularSimilaridade($originalAssunto, $assunto);
  5143.             $scoreDescricao = $calcularSimilaridade($originalDescricao, $desc);
  5144.             $scoreNome = $calcularSimilaridade($originalNome, $nome);
  5145.             $scoreKeywords = $calcularSimilaridade($originalKeywords, $chave);
  5146.             $scoreConteiner = $calcularSimilaridade($originalConteiner, $conteiner);
  5147.             $novaDataDocVal = ($data != "") ? (new \DateTimeImmutable($data))->format('Y-m-d') : null;
  5148.             $scoreDataDoc = ($originalDataDoc === $novaDataDocVal) ? 100.0 : 0.0;
  5149.             $novaDataVencFormatted = $novaDataVencVal ? (new \DateTimeImmutable($novaDataVencVal))->format('Y-m-d') : null;
  5150.             $scoreDataVenc = ($originalDataVenc === $novaDataVencFormatted) ? 100.0 : 0.0;
  5151.             $novaClassIdVal = $classificaObj ? $classificaObj->getId() : null;
  5152.             $scoreClass = ($originalClassId === $novaClassIdVal) ? 100.0 : 0.0;
  5153.             $totalCampos = 8;
  5154.             $porcentagemAssertividade = (
  5155.                 $scoreAssunto + 
  5156.                 $scoreDescricao + 
  5157.                 $scoreNome + 
  5158.                 $scoreKeywords + 
  5159.                 $scoreConteiner + 
  5160.                 $scoreDataDoc + 
  5161.                 $scoreDataVenc + 
  5162.                 $scoreClass
  5163.             ) / $totalCampos;
  5164.             // Salva a porcentagem na entidade
  5165.             $pdf->setAssertividadeIa($porcentagemAssertividade);
  5166.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  5167.             $pdf->setSituacao('OK');
  5168.             $entityManager->flush();
  5169.             $id_pd = $pdf->getId();    
  5170.             $log = new Registro();
  5171.             $log->setOperacao('Conferiu o Documento com id '.$id_pd); 
  5172.             $log->setUser($user_nome_name);
  5173.             $log->setCliente($umlautString);
  5174.             $entityManager->persist($log);
  5175.             $entityManager->flush();
  5176.             $erro = 'ok';
  5177.             $p =  $index_tipo_tipo.' FOI CONFERIDO COM SUCESSO';
  5178.            
  5179.         }   
  5180.         if(isset($_POST["botao_volta"])){
  5181.             $xy = 0 ;
  5182.             $yz = 0 ;
  5183.         }
  5184.         
  5185.         
  5186.         
  5187.         return $this->render('index/qualidade.html.twig', [
  5188.             'documentos' => $documentos,
  5189.             'xy' => $xy,
  5190.             'link' => $link,
  5191.             'pdf'=>$pdf,
  5192.             'p'=>$p,
  5193.             'erro'=>$erro,
  5194.             'pagina' => $pagina,
  5195.             'caminho' =>$caminho,
  5196.             'class' => $class,
  5197.             'all_Url'=>$all_Url,
  5198.             'total'=>$total
  5199.         ]);
  5200.     }
  5201.     
  5202.      #[Route('/metas', name: 'metas')]
  5203.     public function metas( PaginatorInterface $paginator,Request $request,ManagerRegistry $doctrine, EntityManagerInterface $entityManager, SessionInterface $session, MailerInterface $mailer): Response
  5204.     {
  5205.         
  5206.         $fluxos_abertos = $entityManager
  5207.             ->getRepository(Fluxo::class)
  5208.             ->fluxosAbertosComMaiorPrazo();
  5209.             
  5210.          $fluxos_mes = $entityManager
  5211.         ->getRepository(Fluxo::class)
  5212.         ->findMes();
  5213.         $totalFluxos     = 0;
  5214.         $clientesUnicos  = [];
  5215.         $totalCaixas     = 0;
  5216.         $totalDocumentos = 0;
  5217.         $totalImagens    = 0;
  5218.         
  5219.         $avisosPath = $this->getParameter('kernel.project_dir') . '/public/avisos';
  5220.         $avisos = [];
  5221.         
  5222.         if (is_dir($avisosPath)) {
  5223.         
  5224.             $arquivos = scandir($avisosPath);
  5225.         
  5226.             foreach ($arquivos as $arquivo) {
  5227.         
  5228.                 $ext = strtolower(pathinfo($arquivo, PATHINFO_EXTENSION));
  5229.         
  5230.                 if (in_array($ext, ['png', 'jpg', 'jpeg', 'webp'])) {
  5231.         
  5232.                     $avisos[] = '/avisos/' . $arquivo;
  5233.                 }
  5234.             }
  5235.         }
  5236.         
  5237.         shuffle($avisos);
  5238.         
  5239.         
  5240.         foreach ($fluxos_mes as $fluxo) {
  5241.             $totalFluxos++;
  5242.             // 👇 garante cliente único
  5243.             if ($fluxo->getCliente()) {
  5244.                 $clienteId = $fluxo->getCliente()->getId();
  5245.                 $clientesUnicos[$clienteId] = true;
  5246.             }
  5247.             foreach ($fluxo->getCaixas() as $caixa) {
  5248.                 $totalCaixas++;
  5249.                 foreach ($caixa->getDocumentos() as $documento) {
  5250.                     $totalDocumentos++;
  5251.                     $totalImagens += $documento->getQtd();
  5252.                 }
  5253.             }
  5254.         }
  5255.         $formatter = new \IntlDateFormatter(
  5256.             'pt_BR',
  5257.             \IntlDateFormatter::NONE,
  5258.             \IntlDateFormatter::NONE,
  5259.             'America/Sao_Paulo',
  5260.             \IntlDateFormatter::GREGORIAN,
  5261.             'MMMM'
  5262.         );
  5263.         $nomeMes = ucfirst($formatter->format(new \DateTime()));
  5264.         $resumo = [
  5265.             'fluxos'     => $totalFluxos,
  5266.             'clientes'   => count($clientesUnicos), // ✅ não duplica
  5267.             'caixas'     => $totalCaixas,
  5268.             'documentos' => $totalDocumentos,
  5269.             'imagens'    => $totalImagens,
  5270.             'nomeMes'     => $nomeMes
  5271.         ];
  5272.         
  5273.         $a = [];
  5274.         foreach ($fluxos_abertos as $item) {
  5275.             $fluxo = $item[0];
  5276.             $maiorData = $item['prazo'];
  5277.             $cx = 0;
  5278.             $doc = 0;
  5279.             $img = 0;
  5280.             $cliente_id = $fluxo->getCliente()->getId();
  5281.             $cliente = $doctrine->getRepository(Cliente::class)
  5282.             ->createQueryBuilder('c')
  5283.             ->where('c.id = :id')
  5284.             ->setParameter('id', $cliente_id)
  5285.             ->getQuery()
  5286.             ->getOneOrNullResult();
  5287.             foreach ($fluxo->getCaixas() as $caixas) {
  5288.                 $cx++;
  5289.                 foreach ($caixas->getDocumentos() as $docs) {
  5290.                     $doc++;
  5291.                     $img += $docs->getQtd();
  5292.                 }
  5293.             }
  5294.             $a[] = [
  5295.                 'fluxo'       => $fluxo->getId(),
  5296.                 'cliente'     => $cliente->getNome(),
  5297.                 'caixas'      => $cx,
  5298.                 'documentos'  => $doc,
  5299.                 'imagens'     => $img,
  5300.                 'prazo'       => $maiorData,
  5301.             ];
  5302.         }
  5303.                 
  5304.         return $this->render('index/metas_fluxos.html.twig', [
  5305.             'data'=>$a,
  5306.             'resumo'=>$resumo,
  5307.             'avisos' => $avisos
  5308.     
  5309.         ]);
  5310.     }
  5311.     
  5312.         #[Route('/kpis-dashboard', name: 'kpis-dashboard')]
  5313.     public function kpis_dashboard(): Response
  5314.     {
  5315.         return $this->render('index/kpis-dashboard.html.twig');
  5316.     }
  5317.     
  5318.     #[Route('/kpis-dashboard-ia', name: 'kpis-dashboard-ia')]
  5319.     public function kpis_dashboard_ia(): Response
  5320.     {
  5321.         return $this->render('index/documentos_ia.html.twig');
  5322.     }
  5323.     #[Route('/kpis', name: 'kpis')]
  5324.     public function kpis(): Response
  5325.     {
  5326.         return $this->render('index/kpis.html.twig');
  5327.     }
  5328.     
  5329.     // ==========================================
  5330.     // 1. API CAIXA
  5331.     // ==========================================
  5332.     #[Route('/api/kpis/caixas', name: 'api_kpis_caixas', methods: ['POST'])]
  5333.     public function kpis_caixas(Request $request, EntityManagerInterface $entityManager): Response
  5334.     {
  5335.             $conn = $entityManager->getConnection();
  5336.             $de = $request->request->get('de');
  5337.             $ate = $request->request->get('ate');
  5338.         
  5339.             if (!empty($de)) {
  5340.                 if (!empty($ate)) {
  5341.                     $ateComHora = $ate . " 23:59:59";
  5342.                 } else {
  5343.                     $ateComHora = null;
  5344.                 }
  5345.         
  5346.                 $queryStrCx = 'SELECT COUNT(d.id) AS total_cx FROM App\Entity\Cx d WHERE d.createdAt >= :de AND d.caminho IS NOT NULL';
  5347.                 if ($ateComHora) { 
  5348.                     $queryStrCx .= ' AND d.createdAt <= :ate'; 
  5349.                 } else {
  5350.                     $queryStrCx .= ' AND DATE(d.createdAt) = DATE(:de)';
  5351.                 }
  5352.                 $queryCx = $entityManager->createQuery($queryStrCx)->setParameter('de', $de);
  5353.                 if ($ateComHora) { $queryCx->setParameter('ate', $ateComHora); }
  5354.                 $cx = $queryCx->getSingleScalarResult() ?? 0;
  5355.         
  5356.                 $queryStrClientes = "
  5357.                     SELECT 
  5358.                         c.nome AS cliente_nome,
  5359.                         (SELECT COUNT(cx.id) 
  5360.                         FROM App\Entity\Cx cx 
  5361.                         WHERE cx.status != 0 
  5362.                         AND cx.caminho != '' 
  5363.                         AND cx.cliente = c
  5364.                         AND cx.createdAt >= :de " . ($ateComHora ? "AND cx.createdAt <= :ate" : "AND DATE(cx.createdAt) = DATE(:de)") . ") AS total_caixas
  5365.                     FROM App\Entity\ClienteAll c
  5366.                     ORDER BY c.nome ASC
  5367.                 ";
  5368.                 $queryClientes = $entityManager->createQuery($queryStrClientes)->setParameter('de', $de);
  5369.                 if ($ateComHora) { $queryClientes->setParameter('ate', $ateComHora); }
  5370.                 $fed_cliente = $queryClientes->getResult();
  5371.         
  5372.                 $fed_cliente[] = [
  5373.                     'cliente_nome' => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  5374.                     'total_caixas' => 0
  5375.                 ];
  5376.             } else {
  5377.                 $sqlClientes = "
  5378.                     SELECT 
  5379.                         c.nome AS cliente_nome,
  5380.                         (SELECT COUNT(cx.id) FROM cx cx WHERE cx.caminho IS NOT NULL AND cx.cliente_id = c.id) AS total_caixas
  5381.                     FROM cliente_all c ORDER BY c.nome ASC
  5382.                 ";
  5383.                 $fed_cliente = $conn->executeQuery($sqlClientes)->fetchAllAssociative();
  5384.         
  5385.                 $fed_cliente[] = [
  5386.                     'cliente_nome' => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  5387.                     'total_caixas' => 0
  5388.                 ];
  5389.         
  5390.                 $cx = (int) $conn->fetchOne("SELECT COUNT(d.id) FROM cx d WHERE d.status != 0 AND d.caminho != ''");
  5391.             }
  5392.             array_walk_recursive($fed_cliente, function (&$item) {
  5393.         
  5394.                 if (is_string($item) && !preg_match('//u', $item)) {
  5395.         
  5396.                     $item = utf8_encode($item);
  5397.                 }
  5398.             });
  5399.             return $this->json([
  5400.                 'error' => '', 'motivo' => '', 'pagina' => 'kpis', 'h4' => 'TOTAL',
  5401.                 'de' => $de ?? '', 'ate' => $ate ?? '',
  5402.                 'cx' => $cx,
  5403.                 'fed_cliente' => $fed_cliente
  5404.             ]);
  5405.     }
  5406.     // ==========================================
  5407.     // 2. API DOCUMENTO
  5408.     // ==========================================
  5409.     #[Route('/api/kpis/documentos', name: 'api_kpis_documentos', methods: ['POST'])]
  5410.     public function kpis_documentos(Request $request, EntityManagerInterface $entityManager): Response
  5411.     {
  5412.         $conn = $entityManager->getConnection();
  5413.         $de = $request->request->get('de');
  5414.         $ate = $request->request->get('ate');
  5415.         if (!empty($de)) {
  5416.             if (!empty($ate)) {
  5417.                 $ateComHora = $ate . " 23:59:59";
  5418.             } else {
  5419.                 $ateComHora = null;
  5420.             }
  5421.             $queryStrDoc = 'SELECT COUNT(d.id) AS total_documentos FROM App\Entity\Documento d WHERE d.createdAt >= :de';
  5422.             if ($ateComHora) { $queryStrDoc .= ' AND d.createdAt <= :ate'; }
  5423.             $queryDoc = $entityManager->createQuery($queryStrDoc)->setParameter('de', $de);
  5424.             if ($ateComHora) { $queryDoc->setParameter('ate', $ateComHora); }
  5425.             $documento = $queryDoc->getSingleScalarResult() ?? 0;
  5426.             $queryStrClientes = "
  5427.                 SELECT 
  5428.                     c.nome AS cliente_nome,
  5429.                     (SELECT COUNT(d1.id) 
  5430.                     FROM App\Entity\Documento d1 
  5431.                     JOIN d1.cliente c1 
  5432.                     WHERE c1.clienteAll = c
  5433.                     AND d1.createdAt >= :de " . ($ateComHora ? "AND d1.createdAt <= :ate" : "AND DATE(d1.createdAt) = DATE(:de)") . ") AS total_documentos
  5434.                 FROM App\Entity\ClienteAll c
  5435.                 ORDER BY c.nome ASC
  5436.             ";
  5437.             $queryClientes = $entityManager->createQuery($queryStrClientes)->setParameter('de', $de);
  5438.             if ($ateComHora) { $queryClientes->setParameter('ate', $ateComHora); }
  5439.             $fed_cliente = $queryClientes->getResult();
  5440.             $dataTjrj = ['total_documentos' => 0];
  5441.             $anoFiltro = (int) date('Y', strtotime($de));
  5442.             if ($anoFiltro <= 2025) {
  5443.                 try {
  5444.                     $payload = json_encode(['data_inicio' => $de, 'data_fim' => $ate]);
  5445.                     $options = ['http' => ['header' => "Content-Type: application/json\r\n", 'method' => 'POST', 'content' => $payload, 'timeout' => 5]];
  5446.                     $context = stream_context_create($options);
  5447.                     $response = @file_get_contents('https://produtive.arquivosdoc.com.br/api/tjrj', false, $context);
  5448.                     if ($response !== false) { $dataTjrj = json_decode($response, true); }
  5449.                 } catch (\Exception $e) {}
  5450.             }
  5451.             $fed_cliente[] = [
  5452.                 'cliente_nome'     => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  5453.                 'total_documentos' => $dataTjrj['total_documentos'] ?? 0
  5454.             ];
  5455.         } else {
  5456.             $sqlClientes = "
  5457.                 SELECT 
  5458.                     c.nome AS cliente_nome,
  5459.                     (SELECT COUNT(d.id) FROM documento d JOIN cliente s ON s.id = d.cliente_id WHERE s.cliente_all_id = c.id) AS total_documentos
  5460.                 FROM cliente_all c ORDER BY c.nome ASC
  5461.             ";
  5462.             $fed_cliente = $conn->executeQuery($sqlClientes)->fetchAllAssociative();
  5463.             $fed_cliente[] = [
  5464.                 'cliente_nome'     => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  5465.                 'total_documentos' => 140685
  5466.             ];
  5467.             $documento = (int) $conn->fetchOne("SELECT COUNT(d.id) FROM documento d") + 140685;
  5468.         }
  5469.         
  5470.         array_walk_recursive($fed_cliente, function (&$item) {
  5471.             if (is_string($item) && !preg_match('//u', $item)) {
  5472.                 $item = utf8_encode($item);
  5473.             }
  5474.         });
  5475.         return $this->json([
  5476.             'error' => '', 'motivo' => '', 'pagina' => 'kpis', 'h4' => 'TOTAL',
  5477.             'de' => $de ?? '', 'ate' => $ate ?? '',
  5478.             'documento' => $documento,
  5479.             'fed_cliente' => $fed_cliente
  5480.         ]);
  5481.     }
  5482.     // ==========================================
  5483.     // 3. API IMAGENS (E CLIENTES)
  5484.     // ==========================================
  5485.     #[Route('/api/kpis/imagens', name: 'api_kpis_imagens', methods: ['POST'])]
  5486.     public function kpis_imagens(Request $request, EntityManagerInterface $entityManager): Response
  5487.     {
  5488.         $conn = $entityManager->getConnection();
  5489.         $de = $request->request->get('de');
  5490.         $ate = $request->request->get('ate');
  5491.         if (!empty($de)) {
  5492.             if (!empty($ate)) {
  5493.                 $ateComHora = $ate . " 23:59:59";
  5494.             } else {
  5495.                 $ateComHora = null;
  5496.             }
  5497.             $queryStrImg = 'SELECT SUM(d.qtd) AS total_imagens FROM App\Entity\Documento d WHERE d.createdAt >= :de';
  5498.             if ($ateComHora) { $queryStrImg .= ' AND d.createdAt <= :ate'; }
  5499.             $queryImg = $entityManager->createQuery($queryStrImg)->setParameter('de', $de);
  5500.             if ($ateComHora) { $queryImg->setParameter('ate', $ateComHora); }
  5501.             $totalImagens = $queryImg->getSingleScalarResult() ?? 0;
  5502.             $queryStrClientes = "
  5503.                 SELECT 
  5504.                     c.nome AS cliente_nome,
  5505.                     (SELECT SUM(d2.qtd) 
  5506.                     FROM App\Entity\Documento d2 
  5507.                     JOIN d2.cliente c2 
  5508.                     WHERE c2.clienteAll = c
  5509.                     AND d2.createdAt >= :de " . ($ateComHora ? "AND d2.createdAt <= :ate" : "AND DATE(d2.createdAt) = DATE(:de)") . ") AS imagens_total
  5510.                 FROM App\Entity\ClienteAll c
  5511.                 ORDER BY c.nome ASC
  5512.             ";
  5513.             $queryClientes = $entityManager->createQuery($queryStrClientes)->setParameter('de', $de);
  5514.             if ($ateComHora) { $queryClientes->setParameter('ate', $ateComHora); }
  5515.             $fed_cliente = $queryClientes->getResult();
  5516.             $dataTjrj = ['imagens_total' => 0];
  5517.             $anoFiltro = (int) date('Y', strtotime($de));
  5518.             if ($anoFiltro <= 2025) {
  5519.                 try {
  5520.                     $payload = json_encode(['data_inicio' => $de, 'data_fim' => $ate]);
  5521.                     $options = ['http' => ['header' => "Content-Type: application/json\r\n", 'method' => 'POST', 'content' => $payload, 'timeout' => 5]];
  5522.                     $context = stream_context_create($options);
  5523.                     $response = @file_get_contents('https://produtive.arquivosdoc.com.br/api/tjrj', false, $context);
  5524.                     if ($response !== false) { $dataTjrj = json_decode($response, true); }
  5525.                 } catch (\Exception $e) {}
  5526.             }
  5527.             $fed_cliente[] = [
  5528.                 'cliente_nome'  => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  5529.                 'imagens_total' => $dataTjrj['imagens_total'] ?? 0
  5530.             ];
  5531.         } else {
  5532.             $sqlClientes = "
  5533.                 SELECT 
  5534.                     c.nome AS cliente_nome,
  5535.                     (SELECT SUM(d.qtd) FROM documento d JOIN cliente s ON s.id = d.cliente_id WHERE s.cliente_all_id = c.id) AS imagens_total
  5536.                 FROM cliente_all c ORDER BY c.nome ASC
  5537.             ";
  5538.             $fed_cliente = $conn->executeQuery($sqlClientes)->fetchAllAssociative();
  5539.             $fed_cliente[] = [
  5540.                 'cliente_nome'  => 'TRIBUNAL DE JUSTICA DO ESTADO DO RIO DE JANEIRO',
  5541.                 'imagens_total' => 16699398
  5542.             ];
  5543.             $totalImagens = (float) $conn->fetchOne("SELECT SUM(d.qtd) FROM documento d") + 16699398; 
  5544.         }
  5545.         array_walk_recursive($fed_cliente, function (&$item) {
  5546.             if (is_string($item) && !preg_match('//u', $item)) {
  5547.                 $item = utf8_encode($item);
  5548.             }
  5549.         });
  5550.         return $this->json([
  5551.             'error' => '', 'motivo' => '', 'pagina' => 'kpis', 'h4' => 'TOTAL',
  5552.             'de' => $de ?? '', 'ate' => $ate ?? '',
  5553.             'totalImagens' => $totalImagens,
  5554.             'fed_cliente' => $fed_cliente
  5555.         ]);
  5556.     }
  5557.     
  5558.     // ==========================================
  5559.     // 2. API IA
  5560.     // ==========================================
  5561.    
  5562.     #[Route('/api/kpis/documentos/ia', name: 'api_kpis_documentos_ia', methods: ['POST'])]
  5563.     public function kpis_documentos_ia(
  5564.         Request $request,
  5565.         EntityManagerInterface $entityManager
  5566.     ): Response {
  5567.         $conn = $entityManager->getConnection();
  5568.     
  5569.         $de = $request->request->get('de');
  5570.         $ate = $request->request->get('ate');
  5571.     
  5572.         if (!empty($de)) {
  5573.             $ateComHora = !empty($ate) ? $ate . ' 23:59:59' : null;
  5574.     
  5575.             // Total de documentos no período
  5576.             $queryStrDoc = '
  5577.                 SELECT COUNT(d.id) AS total_documentos
  5578.                 FROM App\Entity\Documento d
  5579.                 WHERE d.createdAt >= :de
  5580.             ';
  5581.     
  5582.             if ($ateComHora) {
  5583.                 $queryStrDoc .= ' AND d.createdAt <= :ate';
  5584.             }
  5585.     
  5586.             $queryDoc = $entityManager
  5587.                 ->createQuery($queryStrDoc)
  5588.                 ->setParameter('de', $de);
  5589.     
  5590.             if ($ateComHora) {
  5591.                 $queryDoc->setParameter('ate', $ateComHora);
  5592.             }
  5593.     
  5594.             $documento = (int) $queryDoc->getSingleScalarResult();
  5595.     
  5596.             // Quantidade de documentos com assertividade e média da IA por cliente
  5597.             $queryStrClientes = "
  5598.                 SELECT
  5599.                     c.nome AS cliente_nome,
  5600.     
  5601.                     (
  5602.                         SELECT COUNT(d1.id)
  5603.                         FROM App\Entity\Documento d1
  5604.                         JOIN d1.cliente c1
  5605.                         WHERE c1.clienteAll = c
  5606.                         AND d1.assertividadeIa IS NOT NULL
  5607.                         AND d1.createdAt >= :de
  5608.                         " . ($ateComHora ? "AND d1.createdAt <= :ate" : "") . "
  5609.                     ) AS total_documentos,
  5610.     
  5611.                     (
  5612.                         SELECT AVG(d2.assertividadeIa)
  5613.                         FROM App\Entity\Documento d2
  5614.                         JOIN d2.cliente c2
  5615.                         WHERE c2.clienteAll = c
  5616.                         AND d2.assertividadeIa IS NOT NULL
  5617.                         AND d2.createdAt >= :de
  5618.                         " . ($ateComHora ? "AND d2.createdAt <= :ate" : "") . "
  5619.                     ) AS media_assertividade
  5620.     
  5621.                 FROM App\Entity\ClienteAll c
  5622.                 ORDER BY c.nome ASC
  5623.             ";
  5624.     
  5625.             $queryClientes = $entityManager
  5626.                 ->createQuery($queryStrClientes)
  5627.                 ->setParameter('de', $de);
  5628.     
  5629.             if ($ateComHora) {
  5630.                 $queryClientes->setParameter('ate', $ateComHora);
  5631.             }
  5632.     
  5633.             $fed_cliente = $queryClientes->getResult();
  5634.     
  5635.         } else {
  5636.             // Consulta sem filtro de datas
  5637.             $sqlClientes = "
  5638.                 SELECT
  5639.                     c.nome AS cliente_nome,
  5640.     
  5641.                     COUNT(d.id) AS total_documentos,
  5642.     
  5643.                     AVG(d.assertividade_ia) AS media_assertividade
  5644.     
  5645.                 FROM cliente_all c
  5646.     
  5647.                 LEFT JOIN cliente s
  5648.                     ON s.cliente_all_id = c.id
  5649.     
  5650.                 LEFT JOIN documento d
  5651.                     ON d.cliente_id = s.id
  5652.                     AND d.assertividade_ia IS NOT NULL
  5653.     
  5654.                 GROUP BY c.id, c.nome
  5655.                 ORDER BY c.nome ASC
  5656.             ";
  5657.     
  5658.             $fed_cliente = $conn
  5659.                 ->executeQuery($sqlClientes)
  5660.                 ->fetchAllAssociative();
  5661.     
  5662.             $documento = (int) $conn->fetchOne(
  5663.                 "SELECT COUNT(d.id) FROM documento d"
  5664.             );
  5665.         }
  5666.     
  5667.         // Formata a média para duas casas decimais
  5668.         foreach ($fed_cliente as &$cliente) {
  5669.             if ($cliente['media_assertividade'] !== null) {
  5670.                 $cliente['media_assertividade'] = round(
  5671.                     (float) $cliente['media_assertividade'],
  5672.                     2
  5673.                 );
  5674.             }
  5675.         }
  5676.         unset($cliente);
  5677.     
  5678.         // Corrige possíveis strings com codificação inválida
  5679.         array_walk_recursive($fed_cliente, function (&$item) {
  5680.             if (is_string($item) && !preg_match('//u', $item)) {
  5681.                 $item = utf8_encode($item);
  5682.             }
  5683.         });
  5684.     
  5685.         return $this->json([
  5686.             'error' => '',
  5687.             'motivo' => '',
  5688.             'pagina' => 'kpis',
  5689.             'h4' => 'TOTAL',
  5690.             'de' => $de ?? '',
  5691.             'ate' => $ate ?? '',
  5692.             'documento' => $documento,
  5693.             'fed_cliente' => $fed_cliente
  5694.         ]);
  5695.     }
  5696.     
  5697.     
  5698.     
  5699.     
  5700.     
  5701.       #[Route('/api/etapas/ia', name: 'busca_etapa_para_ia', methods: ['GET'])]
  5702.     public function busca_etapa_para_ia(
  5703.         Request $request,
  5704.         EntityManagerInterface $entityManager
  5705.     ): Response {
  5706.         $clientS3 = new S3Client([
  5707.                 'region'  => 'sa-east-1',
  5708.                 'version' => 'latest',
  5709.                
  5710.             ]);
  5711.         $etapa = $entityManager->createQuery(
  5712.             'SELECT e, f, c
  5713.             FROM App\Entity\Etapa e
  5714.             JOIN e.fluxo f
  5715.             JOIN f.cliente c
  5716.             WHERE e.user = :user
  5717.             AND e.prompt IS NOT NULL
  5718.             AND EXISTS (
  5719.                 SELECT 1
  5720.                 FROM App\Entity\Documento d
  5721.                 JOIN d.caixa cx
  5722.                 WHERE cx.fluxo = f
  5723.                 AND d.tipo IS NULL
  5724.             )
  5725.             ORDER BY e.ordem ASC'
  5726.         )
  5727.         ->setParameter('user', 115)
  5728.         ->setMaxResults(1)
  5729.         ->getOneOrNullResult();
  5730.         
  5731.         if(!$etapa){
  5732.             return $this->json([
  5733.                 'success'=>false,
  5734.                 'message'=>'Nenhuma etapa encontrada.'
  5735.             ],404);
  5736.         }
  5737.         $prompt = $entityManager->createQuery(
  5738.             'SELECT p
  5739.             FROM App\Entity\Prompt p
  5740.             WHERE p.id = :id'
  5741.             
  5742.         )->setParameter('id',$etapa->getPrompt()->getId())
  5743.         ->setMaxResults(1)
  5744.         ->getOneOrNullResult();
  5745.      
  5746.         $fluxo = $etapa->getFluxo();
  5747.         $caixas = $entityManager
  5748.             ->getRepository(Caixa::class)
  5749.             ->findBy([
  5750.                 'fluxo'=>$fluxo
  5751.             ]);
  5752.         $caixaIds = array_map(
  5753.             fn(Caixa $c)=>$c->getId(),
  5754.             $caixas
  5755.         );
  5756.         $documentos = $entityManager
  5757.             ->getRepository(Documento::class)
  5758.             ->createQueryBuilder('d')
  5759.             ->select('partial d.{id,nome,image,createdAt}')
  5760.             ->join('d.caixa', 'c')                // Faz o join com a entidade Caixa
  5761.             ->where('d.caixa IN(:caixas)')
  5762.             ->andWhere('d.tipo IS NULL')
  5763.             ->setParameter('caixas', $caixaIds)
  5764.             ->orderBy('c.id', 'ASC')             // Ordena pelo ID da Caixa (menor para o maior)
  5765.             ->addOrderBy('d.id', 'ASC')          // (Opcional) Depois ordena pelo ID do documento
  5766.             ->getQuery()
  5767.             ->getResult();
  5768.         $docs=[];
  5769.         foreach($documentos as $doc){
  5770.             $cliente_nome= $fluxo->getCliente()->getNome();
  5771.             $clientes= $fluxo->getCliente()->getId();
  5772.             $umlautString =$cliente_nome;
  5773.             $slugger = new AsciiSlugger();
  5774.             $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  5775.             $caminho = strtolower ($teste.'/');
  5776.                             
  5777.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  5778.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  5779.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  5780.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  5781.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  5782.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  5783.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  5784.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  5785.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  5786.             if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  5787.             
  5788.             if($fluxo->getCliente()->getExtraFields()!= "local"){
  5789.                 $cmd = $clientS3->getCommand('GetObject', [
  5790.                     'Bucket' => 'arquivosdoc',
  5791.                     'Key'    => $caminho. $doc->getImage(), 
  5792.                 ]);
  5793.                 
  5794.                 $req = $clientS3->createPresignedRequest($cmd,  '+4 hours');
  5795.                 $all_Url = (string) $req->getUri();
  5796.             }else{
  5797.                $all_Url =$doc->getImage();
  5798.             }
  5799.             $docs[]=[
  5800.                 'id'=>$doc->getId(),
  5801.                 'image'=>$all_Url,
  5802.             ];
  5803.         }
  5804.         return $this->json([
  5805.             'success'=>true,
  5806.             'prompt'=>[
  5807.                 'id' => $prompt->getId(),
  5808.                 'campo1' => $prompt->getNome(),
  5809.                 'campo2' => $prompt->getAssunto(),
  5810.                 'campo3' => $prompt->getKeywords(),
  5811.                 'data' => $prompt->getDataDocumento(),
  5812.                 'tipos' => $prompt->getTipos(),
  5813.                 'classificacoes' => $prompt->getClassificacoes(),
  5814.                 'letras' => $prompt->getLetras(),
  5815.             ],
  5816.             'documentos'=>$docs,
  5817.         ]);
  5818.     }
  5819.     
  5820.     
  5821.     
  5822.      #[Route('/api/etapas/ia/salvar', name: 'salvar_resultado_ia', methods: ['POST'])]
  5823.     public function salvarResultadoIa(
  5824.         Request $request,
  5825.         EntityManagerInterface $entityManager,
  5826.         DocumentoRepository $documentoRepository,
  5827.         TipoRepository $tipoRepository,
  5828.         CaixaRepository $caixaRepository,
  5829.         ClassificacaoRepository $classificacaoRepository
  5830.     ): JsonResponse {
  5831.         // Recebe o JSON enviado pelo Worker Python
  5832.         $dataPayload = json_decode($request->getContent(), true);
  5833.         $dadosAlterados = [];
  5834.         if (!$dataPayload || !isset($dataPayload['documento_id'])) {
  5835.             return $this->json([
  5836.                 'success' => false,
  5837.                 'message' => 'Payload inválido. "documento_id" é obrigatório.'
  5838.             ], Response::HTTP_BAD_REQUEST);
  5839.         }
  5840.         $documentoId = $dataPayload['documento_id'];
  5841.         $dados = $dataPayload['dados_extraidos'] ?? [];
  5842.         // 1. Busca o Documento PDF no banco
  5843.         $pdf = $documentoRepository->find($documentoId);
  5844.         if (!$pdf) {
  5845.             return $this->json([
  5846.                 'success' => false,
  5847.                 'message' => "Documento ID {$documentoId} não encontrado."
  5848.             ], Response::HTTP_NOT_FOUND);
  5849.         }
  5850.          $caixaObj = $caixaRepository->findOneBy(['id'=>$pdf->getCaixa()->getId()]);
  5851.          $fluxo = $caixaObj->getFluxo();
  5852.         
  5853.         $dadosAlterados['Repositor'] = $caixaObj->getNome();
  5854.         $tipoNome = $dados['tipos'] ?? null;
  5855.         
  5856.         if ($tipoNome) {
  5857.             $tipoObj = $tipoRepository->findOneBy(['nome' => trim($tipoNome),'cliente'=>$pdf->getCliente()]);
  5858.             if ($tipoObj) {
  5859.                 $pdf->setTipo($tipoObj);
  5860.                 $dadosAlterados['Tipo'] = $tipoObj->getNome();
  5861.             }
  5862.         }
  5863.         
  5864.        
  5865.         $classificacaoTexto = $dados['classificacoes'] ?? null;
  5866.         $classificacaoObj = null;
  5867.         if ($classificacaoTexto) {
  5868.           
  5869.             if (!$classificacaoObj) {
  5870.                 $classificacaoObj = $classificacaoRepository->findOneBy(['nome' => trim($classificacaoTexto),'cliente'=>$pdf->getCliente()]);
  5871.             }
  5872.             if ($classificacaoObj) {
  5873.                 $pdf->setClassificacao($classificacaoObj);
  5874.                 $dadosAlterados['TDD'] = $classificacaoObj->getNome();
  5875.             }
  5876.         }
  5877.         $dataDocString = $dados['data'] ?? null;
  5878.         
  5879.         if (!empty($dataDocString) && $dataDocString !== 'null' && $dataDocString !== 'undefined') {
  5880.             try {
  5881.                 $dataDocumento = \DateTimeImmutable::createFromFormat('!Y-m-d', (string)$dataDocString)
  5882.                     ?: \DateTimeImmutable::createFromFormat('!d/m/Y', (string)$dataDocString);
  5883.                 if ($dataDocumento !== false) {
  5884.                     
  5885.                     $pdf->setDataDocumento($dataDocumento);
  5886.                     $dadosAlterados['Data Documento'] = $dataDocString;
  5887.                     if ($classificacaoObj && method_exists($classificacaoObj, 'getFaseIntermediaria')) {
  5888.                         $faseRaw = $classificacaoObj->getFaseIntermediaria();
  5889.                         if ($faseRaw !== null && $faseRaw !== '' && $faseRaw !== 'null') {
  5890.                             
  5891.                             if (preg_match('/\d+/', (string)$faseRaw, $matches)) {
  5892.                                 $anosParaSomar = (int) $matches[0];
  5893.                                 if ($anosParaSomar > 0) {
  5894.                                     $vencimento = $dataDocumento->modify("+{$anosParaSomar} years");
  5895.                                     $pdf->setVencimentoDocumento($vencimento);
  5896.                                 }
  5897.                             }
  5898.                         }
  5899.                     }
  5900.                 }
  5901.             } catch (\Throwable $e) {
  5902.             }
  5903.         }
  5904.         
  5905.        if (isset($dados['campo1'])) {
  5906.             $pdf->setNome($dados['campo1']);
  5907.             $dadosAlterados['Nome'] = $dados['campo1'];
  5908.         }
  5909.         
  5910.         if (isset($dados['campo2'])) {
  5911.             $pdf->setAssunto($dados['campo2']);
  5912.             $dadosAlterados['Assunto'] = $dados['campo2'];
  5913.         }
  5914.         
  5915.         if (isset($dados['campo3'])) {
  5916.             $pdf->setKeywords($dados['campo3']);
  5917.             $dadosAlterados['Palavra-Chave'] = $dados['campo3'];
  5918.         }
  5919.         $pdf->setUserIndex("LEONARDO DE SOUZA CRUZEIRO");
  5920.         
  5921.         $pdf->setIndexAt(
  5922.             new \DateTimeImmutable('now', new \DateTimeZone('America/Sao_Paulo'))
  5923.         );
  5924.         
  5925.         
  5926.         // Localização / IP
  5927.         $ip_cliente = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])[0] : $_SERVER['REMOTE_ADDR'];
  5928.         $geo = @json_decode(@file_get_contents("http://ip-api.com/json/{$ip_cliente}"));
  5929.         $localizacao = ($geo && $geo->status === 'success') 
  5930.             ? "IP: {$ip_cliente} | País: {$geo->country} | Estado: {$geo->regionName} | Cidade: {$geo->city} | CEP: {$geo->zip} | ISP: {$geo->isp}"
  5931.             : "IP: {$ip_cliente} | Localização não disponível";
  5932.         $log = new Registro();
  5933.         $log->setOperacao(
  5934.             sprintf(
  5935.                 "Indexação-(Dados Indexado: %s)",
  5936.                 json_encode($dadosAlterados, JSON_UNESCAPED_UNICODE)
  5937.             )
  5938.         );
  5939.         $log->setIp($localizacao);
  5940.         $log->setFluxo($fluxo);
  5941.         $log->setData(new \DateTimeImmutable('America/Sao_Paulo'));
  5942.         $log->setIdUser($entityManager->getRepository(User::class)->find(115));
  5943.         $entityManager->persist($log);
  5944.         $entityManager->flush();
  5945.         
  5946.         return $this->json([
  5947.             'success' => true,
  5948.             'message' => 'Documento indexado com sucesso!',
  5949.             'documento_id' => $pdf->getId()
  5950.         ]);
  5951.     }
  5952.     
  5953.     #[Route('/api/documentos/vps', name: 'api_documento_store', methods: ['POST'])]
  5954.     public function store(Request $request, EntityManagerInterface $em): JsonResponse
  5955.     {
  5956.         
  5957.         $data = json_decode($request->getContent(), true);
  5958.         if (!$data) {
  5959.             return $this->json(['error' => 'Payload inválido'], 400);
  5960.         }
  5961.         try {
  5962.             // 2. Busca das entidades na VPS (onde o banco está)
  5963.             $caixa = $em->getRepository(Caixa::class)->find($data['caixaId']);
  5964.             $cliente = $em->getRepository(Cliente::class)->find($data['clienteId']);
  5965.             $user = $em->getRepository(User::class)->find($data['userId']);
  5966.             if (!$caixa || !$cliente || !$user) {
  5967.                 return $this->json(['error' => 'Entidades não encontradas'], 404);
  5968.             }
  5969.             // 3. Criação do documento com os dados já processados na máquina Gamer
  5970.             $documento = new Documento();
  5971.             $documento->setCaixa($caixa);
  5972.             $documento->setCliente($cliente);
  5973.             $documento->setUser($user);
  5974.             $documento->setNome($data['nome'] ?? '');
  5975.             $documento->setAssunto($data['assunto'] ?? null);
  5976.             $documento->setKeywords($data['keywords'] ?? null);
  5977.             $documento->setConteiner($data['conteiner'] ?? '');
  5978.             $documento->setImage($data['image'] ?? null);
  5979.             $documento->setOcr($data['ocr'] ?? null);
  5980.             $documento->setQtd($data['qtd'] ?? 0);
  5981.             $documento->setQtd1($data['qtd1'] ?? 0);
  5982.             $documento->setImgs($data['imgs'] ?? null);
  5983.             if (!empty($data['tipoId'])) {
  5984.                 $tipo = $em->getRepository(Tipo::class)->find($data['tipoId']);
  5985.                 if ($tipo) {
  5986.                     $documento->setTipo($tipo);
  5987.                 }
  5988.             }
  5989.             // 4. Salva no banco da VPS
  5990.             $em->persist($documento);
  5991.             $em->flush();
  5992.             return $this->json(['status' => 'sucesso', 'id' => $documento->getId()], 201);
  5993.         } catch (\Throwable $e) {
  5994.             return $this->json(['error' => $e->getMessage()], 500);
  5995.         }
  5996.     }
  5997.     
  5998.     
  5999.     #[Route('/api/qualidade/salvar', name: 'api_qualidade_salvar', methods: ['POST'])]
  6000.     public function salvarQualidadeApi(
  6001.         Request $request, 
  6002.         ManagerRegistry $doctrine, 
  6003.         EntityManagerInterface $entityManager, 
  6004.         DriveToOneDriveService $service
  6005.     ): JsonResponse {
  6006.         try {
  6007.             $data = json_decode($request->getContent(), true);
  6008.     
  6009.             if (!$data || !isset($data['documento_id'])) {
  6010.                 return new JsonResponse([
  6011.                     'success' => false, 
  6012.                     'message' => 'Dados inválidos ou ID do documento não fornecido.'
  6013.                 ], 400);
  6014.             }
  6015.     
  6016.             $pdf = $doctrine->getRepository(Documento::class)->find($data['documento_id']);
  6017.     
  6018.             if (!$pdf) {
  6019.                 return new JsonResponse([
  6020.                     'success' => false, 
  6021.                     'message' => 'Documento não encontrado.'
  6022.                 ], 404);
  6023.             }
  6024.     
  6025.             // 1. Capturar os valores originais da IA antes de atualizar
  6026.             $originalAssunto = $pdf->getAssunto();
  6027.             $originalDescricao = $pdf->getExtraFields();
  6028.             $originalNome = $pdf->getNome();
  6029.             $originalKeywords = $pdf->getKeywords();
  6030.             $originalConteiner = $pdf->getConteiner();
  6031.             
  6032.             $originalDataDoc = $pdf->getDataDocumento() ? $pdf->getDataDocumento()->format('Y-m-d') : null;
  6033.             $originalDataVenc = $pdf->getVencimentoDocumento() ? $pdf->getVencimentoDocumento()->format('Y-m-d') : null;
  6034.             
  6035.             $originalClassId = $pdf->getClassificacao() ? $pdf->getClassificacao()->getId() : null;
  6036.     
  6037.             // 2. Aplicar as alterações enviadas pelo humano
  6038.             $clientes = $pdf->getCliente() ? $pdf->getCliente()->getId() : null;
  6039.     
  6040.             if (!empty($data['data_documento'])) {
  6041.                 $pdf->setDataDocumento(new \DateTimeImmutable($data['data_documento']));
  6042.             }
  6043.     
  6044.             if (!empty($data['data_vencimento'])) {
  6045.                 $pdf->setVencimentoDocumento(new \DateTimeImmutable($data['data_vencimento']));
  6046.             }
  6047.     
  6048.             if (!empty($data['classificacao_id'])) {
  6049.                 $classificacaoObj = $doctrine->getRepository(Classificacao::class)->find($data['classificacao_id']);
  6050.                 if ($classificacaoObj) {
  6051.                     $pdf->setClassificacao($classificacaoObj);
  6052.                 }
  6053.             }
  6054.             
  6055.             $clienteExtraFields = $entityManager->createQueryBuilder()
  6056.                     ->select('c.extraFields')
  6057.                     ->from(Cliente::class, 'c')
  6058.                     ->where('c.id = :id')
  6059.                     ->setParameter('id', $clientes)
  6060.                     ->getQuery()
  6061.                     ->getSingleScalarResult();
  6062.     
  6063.             if ($clienteExtraFields == "local") {
  6064.                 $pdf->setRenomear(1);
  6065.             }
  6066.     
  6067.             $pdf->setAssunto($data['assunto'] ?? null);
  6068.             $pdf->setExtraFields($data['descricao'] ?? null);
  6069.             $pdf->setNome($data['nome'] ?? null);
  6070.             $pdf->setKeywords($data['palavra_chave'] ?? null);
  6071.             $pdf->setConteiner($data['container'] ?? null);
  6072.     
  6073.             // 3. Cálculo da assertividade usando similaridade de strings e verificação de datas/ids
  6074.             $calcularSimilaridade = function(?string $original, ?string $novo): float {
  6075.                 $original = trim($original ?? '');
  6076.                 $novo = trim($novo ?? '');
  6077.     
  6078.                 if ($original === '' && $novo === '') {
  6079.                     return 100.0;
  6080.                 }
  6081.                 
  6082.                 if ($original === '' || $novo === '') {
  6083.                     return 0.0;
  6084.                 }
  6085.     
  6086.                 similar_text($original, $novo, $percentual);
  6087.                 return $percentual; 
  6088.             };
  6089.     
  6090.             $scoreAssunto = $calcularSimilaridade($originalAssunto, $data['assunto'] ?? null);
  6091.             $scoreDescricao = $calcularSimilaridade($originalDescricao, $data['descricao'] ?? null);
  6092.             $scoreNome = $calcularSimilaridade($originalNome, $data['nome'] ?? null);
  6093.             $scoreKeywords = $calcularSimilaridade($originalKeywords, $data['palavra_chave'] ?? null);
  6094.             $scoreConteiner = $calcularSimilaridade($originalConteiner, $data['container'] ?? null);
  6095.     
  6096.             $novaDataDoc = !empty($data['data_documento']) ? (new \DateTimeImmutable($data['data_documento']))->format('Y-m-d') : null;
  6097.             $scoreDataDoc = ($originalDataDoc === $novaDataDoc) ? 100.0 : 0.0;
  6098.     
  6099.             $novaDataVenc = !empty($data['data_vencimento']) ? (new \DateTimeImmutable($data['data_vencimento']))->format('Y-m-d') : null;
  6100.             $scoreDataVenc = ($originalDataVenc === $novaDataVenc) ? 100.0 : 0.0;
  6101.     
  6102.             $novaClassId = !empty($data['classificacao_id']) ? (int)$data['classificacao_id'] : null;
  6103.             $scoreClass = ($originalClassId === $novaClassId) ? 100.0 : 0.0;
  6104.     
  6105.             $totalCampos = 8;
  6106.             $porcentagemAssertividade = (
  6107.                 $scoreAssunto + 
  6108.                 $scoreDescricao + 
  6109.                 $scoreNome + 
  6110.                 $scoreKeywords + 
  6111.                 $scoreConteiner + 
  6112.                 $scoreDataDoc + 
  6113.                 $scoreDataVenc + 
  6114.                 $scoreClass
  6115.             ) / $totalCampos;
  6116.     
  6117.             // Salva a porcentagem na entidade
  6118.             $pdf->setAssertividadeIa($porcentagemAssertividade);
  6119.     
  6120.             // 4. Finalização
  6121.             $user_nome_name = $entityManager->createQueryBuilder()
  6122.                 ->select('u.nome')
  6123.                 ->from(User::class, 'u')
  6124.                 ->where('u.id = :id')
  6125.                 ->setParameter('id', $data['etapa_user'])
  6126.                 ->getQuery()
  6127.                 ->getSingleScalarResult();
  6128.             
  6129.             $pdf->setUserIndex($user_nome_name);
  6130.             $pdf->setIndexAt(new \DateTimeImmutable('America/Sao_Paulo'));
  6131.             $pdf->setSituacao('OK');
  6132.             
  6133.             $entityManager->flush();
  6134.     
  6135.             return new JsonResponse([
  6136.                 'success' => true,
  6137.                 'message' => 'Documento conferido com sucesso!',
  6138.             ]);
  6139.     
  6140.         } catch (\Exception $e) {
  6141.             return new JsonResponse([
  6142.                 'success' => false,
  6143.                 'message' => 'Erro interno: ' . $e->getMessage()
  6144.             ], 500);
  6145.         }
  6146.     }
  6147.     
  6148.     
  6149.     #[Route('/api/etapas/renomear', name: 'busca_etapa_para_renomeara', methods: ['GET'])]
  6150.     public function busca_etapa_para_renomear(
  6151.         Request $request,
  6152.         EntityManagerInterface $entityManager
  6153.     ): Response {
  6154.         $clientS3 = new S3Client([
  6155.                 'region'  => 'sa-east-1',
  6156.                 'version' => 'latest',
  6157.                
  6158.             ]);
  6159.         $documentos = $entityManager
  6160.             ->getRepository(Documento::class)
  6161.             ->createQueryBuilder('d')
  6162.             ->leftJoin('d.cliente', 'c')
  6163.             ->leftJoin('d.classificacao', 'cl')
  6164.             ->leftJoin('d.caixa', 'cx')
  6165.             ->select('partial d.{id,nome,image,createdAt}')
  6166.             ->addSelect('partial c.{id,nome,extraFields}')
  6167.             ->addSelect('partial cl.{id,nome}')
  6168.             ->addSelect('partial cx.{id,nome}')
  6169.             ->where('d.renomear = 1')
  6170.             ->orderBy('d.id', 'ASC')
  6171.             ->getQuery()
  6172.             ->getResult();
  6173.         $docs=[];
  6174.         
  6175.         foreach($documentos as $doc){
  6176.             $cliente_nome= $doc->getCliente()->getNome();
  6177.             $clientes= $doc->getCliente()->getId();
  6178.             $umlautString =$cliente_nome;
  6179.             $slugger = new AsciiSlugger();
  6180.             $teste=$slugger->slug($umlautString, $seperator = '-')->toString();
  6181.             $caminho = strtolower ($teste.'/');
  6182.                             
  6183.             if($clientes == 14){$caminho='cartorio-1deg-oficio-de-volta-redonda-rj/';}
  6184.             if($clientes == 83){$caminho='casf-corretora-apolice-diversos/';}
  6185.             if($clientes == 35){$caminho='pmecj-sp-saude/';}
  6186.             if($clientes == 107){$caminho='pmecj-sp-execucao-fiscal/';}
  6187.             if($clientes ==  4){$caminho='cartorio-souza-reis-barra-mansa/';}
  6188.             if($clientes ==  112){$caminho='saae-cartao-de-ponto/';}
  6189.             if($clientes ==  15){$caminho='cbsi-dossies/';}
  6190.             if($clientes ==  55){$caminho='casf-gerep-contratos-de-prestadores-de-saude-pj/';}
  6191.             if($clientes ==  13){$caminho='casa-de-saude-santa-maria-c-s-s.M/';}
  6192.             if($clientes ==  127){$caminho='pmecj-s-a.A) - ALMOXARIFADO E PATRIMÔNIO/';}
  6193.             
  6194.             if($doc->getCliente()->getExtraFields()!= "local"){
  6195.                 $cmd = $clientS3->getCommand('GetObject', [
  6196.                     'Bucket' => 'arquivosdoc',
  6197.                     'Key'    => $caminho. $doc->getImage(), 
  6198.                 ]);
  6199.                 
  6200.                 $req = $clientS3->createPresignedRequest($cmd, '+30 minutes');
  6201.                 $all_Url = (string) $req->getUri();
  6202.             }else{
  6203.                $all_Url =$doc->getImage();
  6204.             }
  6205.            $docs[] = [
  6206.                 'id' => $doc->getId(),
  6207.                 'nome' => $doc->getNome(),
  6208.                 'cliente' => $cliente_nome,
  6209.                 'image' => $all_Url,
  6210.                 'caixa' => $doc->getCaixa()?->getNome() ?? 'SEM CAIXA',
  6211.                 'cla' => $doc->getClassificacao()?->getNome() ?? 'SEM CLASSIFICAÇÃO',
  6212.             ];
  6213.         }
  6214.         return $this->json([
  6215.             'success'=>true,
  6216.             'documentos'=>$docs,
  6217.         ]);
  6218.     }
  6219.     
  6220.     #[Route('/api/etapas/atualizar-renomear', name: 'busca_etapa_atualizar-renomear', methods: ['POST'])]
  6221.     public function atualizarRenomear(Request $request, EntityManagerInterface $entityManager): JsonResponse
  6222.     {
  6223.         // Pega os dados enviados em JSON pelo Python
  6224.         $data = json_decode($request->getContent(), true);
  6225.         
  6226.         $documentoId = $data['documento_id'] ?? null;
  6227.         $caminho = $data['caminho'] ?? null;
  6228.         if (!$documentoId) {
  6229.             return new JsonResponse([
  6230.                 'success' => false,
  6231.                 'message' => 'ID do documento não informado.'
  6232.             ], 400);
  6233.         }
  6234.         // Busca o documento no banco de dados
  6235.         $documento = $entityManager->getRepository(Documento::class)->find($documentoId);
  6236.         if (!$documento) {
  6237.             return new JsonResponse([
  6238.                 'success' => false,
  6239.                 'message' => 'Documento não encontrado.'
  6240.             ], 404);
  6241.         }
  6242.         
  6243.         $documento->setRenomear(0); 
  6244.         $documento->setMovimentacao($caminho);
  6245.     
  6246.         $entityManager->flush();
  6247.         return new JsonResponse([
  6248.             'success' => true,
  6249.             'message' => "Documento {$documentoId} atualizado com sucesso (renomear = 0)."
  6250.         ]);
  6251.     }
  6252.     
  6253.     
  6254.     
  6255.     
  6256.     
  6257.     
  6258.     public function configureDashboard(): Dashboard
  6259.     {
  6260.         return Dashboard::new()
  6261.             ->setTitle('IndexDoc')
  6262.             ->setFaviconPath('./img/icon.png');   
  6263.     }
  6264.     
  6265.     public function configureMenuItems(): iterable
  6266.     {
  6267.         // yield MenuItem::linkToDashboard('Dashboard', 'fa fa-home');
  6268.         // yield MenuItem::linkToCrud('The Label', 'fas fa-list', EntityClass::class);
  6269.     }
  6270. }