src/Controller/AppExternoController.php line 4258

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  4. use Symfony\Component\HttpFoundation\Response;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\Routing\Annotation\Route;
  7. use Symfony\Component\HttpFoundation\JsonResponse;
  8. use App\Entity\EntregaPedido;
  9. use App\Entity\PedidoAcumulado;
  10. use App\Entity\ProdutoBling;
  11. use App\Entity\User;
  12. use App\Entity\MensagemMural;
  13. use App\Entity\ValeSolicitacao;
  14. use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
  15. use Symfony\Contracts\HttpClient\HttpClientInterface;
  16. use App\Entity\MensagemColeta;
  17. use Symfony\Component\HttpKernel\KernelInterface;
  18. use Symfony\Bundle\FrameworkBundle\Console\Application;
  19. use Symfony\Component\Console\Input\ArrayInput;
  20. use Symfony\Component\Console\Output\BufferedOutput;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Dompdf\Dompdf;
  23. use Dompdf\Options;
  24. use App\Entity\LancamentoClienteDrive;
  25. use App\Entity\ClienteDrive;
  26. use App\Services\BlingService;
  27. use App\Services\LogAcoesService;
  28. use App\Entity\PagamentoPedidoCreditoDebito;
  29. use App\Entity\ContatoBling;
  30. use App\Entity\LancamentoFinanceiroColaborador;
  31. use App\Entity\OrdemServico;
  32. use App\Entity\LogAcoes;
  33. use App\Entity\EntregaRoute;
  34. use App\Entity\DemandaPedido;
  35. class AppExternoController extends BaseController
  36. {
  37.   
  38.     ################ UPLOAD INDIVIDUAL
  39.     
  40.     /**
  41.      * @Route("/upload_imagem_open", name="upload_imagem_open", methods={"GET"})
  42.      */
  43.     public function uploadImageOpen(Request $request): Response
  44.     {
  45.         return $this->render('upload_imagem/index.html.twig');
  46.     }
  47.     
  48.     /**
  49.      * @Route("/acesso_direto_motorista", name="acesso_direto_motorista", methods={"GET"})
  50.      */
  51.     public function acessoDiretoMotorista(Request $request): Response
  52.     {
  53.         $usuarios = [];
  54.         $colaboradores $this->getDoctrine()->getRepository(User::class)->findBy([], ['email'=>'asc']);
  55.         
  56.         foreach ($colaboradores as $colaborador) {
  57.             
  58.             if(in_array($colaborador->getEmail(),['bruno@moveispollo.com.br''willian@moveispollo.com.br''primo@moveispollo.com.br''guilherme''douglas''neto''richardy''willian''junior''fabio''joao_luiz''maria''bigode''nelson''gregory''eduardo''andre''emanuel''kevin''adriel''nicholas'])){
  59.                 continue;
  60.             }
  61.             
  62.             $usuarios[] = [
  63.                 'id' => $colaborador->getId(),
  64.                 'name' => strtoupper($colaborador->getEmail()),
  65.                 'email' => $colaborador->getEmail(),
  66.             ];
  67.         }
  68.         
  69.         return $this->render('upload_imagem/index-motorista.html.twig', ['colaboradores'=>$usuarios]);
  70.     }
  71.     
  72.     ################ UPLOAD INDIVIDUAL
  73.     
  74.     /**
  75.      * @Route("/app-externo/pedidos_proximos", name="pedidos_proximos", methods={"POST"})
  76.      */
  77.     public function pedidosProximos(Request $request): Response
  78.     {
  79.         
  80.         $pedidos = [];
  81.         $data json_decode($request->getContent(), false);
  82.         
  83.         $pedidoEncontado $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
  84.         
  85.         if(!$pedidoEncontado instanceof EntregaPedido) {
  86.             return new JsonResponse($pedidos200);
  87.         }
  88.         
  89.         if($pedidoEncontado->getLatitude()==null || $pedidoEncontado->getLongitude()==null) {
  90.             return new JsonResponse($pedidos200);
  91.         }
  92.         
  93.         // Exemplo de uso
  94.         $latitude $pedidoEncontado->getLatitude();
  95.         $longitude $pedidoEncontado->getLongitude();
  96.         $maxDistance $data->raio;
  97.         //$statuses = ['pendente', 'recebido', 'cotaca', 'pendente_admin', 'aguardando_pagamento'];
  98.         $statuses = ['pendente'];
  99.         
  100.         $results $this->getDoctrine()->getRepository(EntregaPedido::class)
  101.         ->findNearbyLocationsWithStatus($latitude$longitude$maxDistance$statuses);
  102.         
  103.         foreach ($results as $location) {
  104.             
  105.             if($location['id']==$data->id) {
  106.                 continue;
  107.             }
  108.             
  109.             $numeroPedido $location['pedido'];
  110.             
  111.             if($numeroPedido=='' || $numeroPedido==null) {
  112.                 $numeroPedido $location['nota_fiscal'];
  113.             }
  114.             
  115.             $distancia number_format($location['distance'], 3);
  116.             $link 'https://www.google.com/maps?q='.$location['latitude'].','.$location['longitude'];
  117.             $pedidos[] = ['id'=>$location['id'], 'pedido'=>$numeroPedido'distancia'=>$distancia'coordenadas'=>$location['latitude'].','.$location['longitude'], 'link'=>$link];
  118.         }
  119.         
  120.         return new JsonResponse($pedidos200);
  121.     }
  122.     
  123.     /**
  124.      * @Route("/app-externo/decodifica-endereco", name="decodifica_endereco")
  125.      */
  126.     public function decodificaEnderecoAction(Request $request): Response
  127.     {
  128.         $address 'Rua 209,  100,  ,  Setor Coimbra,  Goiânia/GO,  74.530-070,  ';
  129.         $coordenadas $this->decodificaEndereco($address);
  130.         return new JsonResponse($coordenadas200);
  131.         
  132.         /*
  133.         
  134.             46388
  135.             latitude: -16.6762553,
  136.             longitude: -49.292202
  137.             
  138.             -16.675385, -49.289547
  139.         
  140.             UPDATE entrega_pedido set latitude=-16.675385, longitude=-49.289547 WHERE id=9393
  141.             
  142.             Apagar pois é original
  143.             -16.676255, -49.292202
  144.             UPDATE entrega_pedido set latitude=-16.676255, longitude=-49.292202 WHERE id=10873 === Pedido 47766
  145.         */
  146.     }
  147.     
  148.     public function decodificaEndereco($address)
  149.     {
  150.         
  151.         // Endereço que você deseja converter
  152.         //$address = "Rua 205, 641, QD 98 LT 83A ST COIMBRA, St Coimbra, Goiânia/GO, 74530030,";
  153.         
  154.         // Sua chave de API do Google
  155.         $apiKey "AIzaSyBpmGesyT1jy7cdCtdDXwptTseDfBzxiGc";
  156.         
  157.         // Formatar o endereço para uso na URL da API
  158.         $address urlencode($address);
  159.         
  160.         // URL da API de Geocoding do Google
  161.         $url "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key={$apiKey}";
  162.         
  163.         // Inicializar cURL
  164.         $ch curl_init();
  165.         
  166.         // Configurar as opções do cURL
  167.         curl_setopt($chCURLOPT_URL$url);
  168.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  169.         
  170.         // Executar a requisição e obter a resposta
  171.         $response curl_exec($ch);
  172.         
  173.         // Verificar se houve algum erro
  174.         if(curl_errno($ch)) {
  175.             return false;
  176.             exit;
  177.         }
  178.         
  179.         // Fechar o cURL
  180.         curl_close($ch);
  181.         
  182.         // Decodificar a resposta JSON
  183.         $responseData json_decode($responsetrue);
  184.         
  185.         $coordenadas = [];
  186.         
  187.         // Verificar o status da resposta
  188.         if($responseData['status'] == 'OK') {
  189.             
  190.             // Obter as coordenadas
  191.             $latitude $responseData['results'][0]['geometry']['location']['lat'];
  192.             $longitude $responseData['results'][0]['geometry']['location']['lng'];
  193.             
  194.             $coordenadas['latitude'] = $latitude;
  195.             $coordenadas['longitude'] = $longitude;
  196.         } else {
  197.             return false;
  198.         }
  199.         return $coordenadas;
  200.     }
  201.     
  202.     /**
  203.      * @Route("/app-externo/lista-log-acoes/{data_inicial}/{data_final}", name="lista_logs_acoes")
  204.      */
  205.     public function listaLogsAcoes(Request $requestHttpClientInterface $client$data_inicial$data_final): Response
  206.     {
  207.         
  208.         $logsData = [];
  209.         
  210.         if($this->isAdmin()) {
  211.             
  212.             $logsEntity $this->getDoctrine()->getRepository(LogAcoes::class)->getLogs($data_inicial$data_final);
  213.             
  214.             foreach ($logsEntity as $log) {
  215.                 $logsData[] = [
  216.                     'id' => $log->getId(),
  217.                     'pedido' => $log->getPedido(),
  218.                     'origem' => $log->getOrigem(),
  219.                     'acao' => $log->getAcao(),
  220.                     'usuario' => $log->getUsuario()->getEmail(),
  221.                     'data' => $log->getCreatedAt()->format('d/m/Y H:i')
  222.                 ];
  223.             }
  224.         }
  225.         
  226.         return new JsonResponse($logsData200);
  227.     }
  228.     
  229.     private function getStatusCorretoNome($status) {
  230.         $status strtoupper($status);
  231.             
  232.         switch ($status) {
  233.             
  234.             case 'PENDENTE':
  235.                 $status 'À Entregar';
  236.                 break;
  237.                 
  238.             case 'RECEBIDO':
  239.                 $status 'Em Andamento';
  240.                 break;
  241.                 
  242.             case 'TRANSITO':
  243.                 $status 'Em Trânsito';
  244.                 break;
  245.             
  246.             case 'ENTREGUE':
  247.                 $status 'À Finalizar';
  248.                 break;
  249.                 
  250.             case 'PENDENTE_ADMIN':
  251.                 $status 'Pendente';
  252.                 break;
  253.                 
  254.             case 'COTACAO':
  255.                 $status 'Cotação';
  256.                 break;
  257.                 
  258.             case 'AGUARDANDO_PAGAMENTO':
  259.                 $status 'Aguardando Pagamento';
  260.                 break;
  261.                 
  262.             case 'ACEITO':
  263.                 $status 'Aceito';
  264.                 break;
  265.                 
  266.             default:
  267.                 // code...
  268.                 break;
  269.         }
  270.         
  271.         return $status;
  272.     }
  273.     
  274.     function dentroIntervaloAbrirPedidosPendentes() {
  275.         
  276.         $agora = new \DateTime();
  277.         $horaAtual $agora->format('H:i');
  278.     
  279.         // Definir os intervalos de tempo permitidos
  280.         $intervalos = [
  281.             ['08:00''08:30'],
  282.             ['10:00''10:30'],
  283.             ['13:00''14:00']
  284.         ];
  285.     
  286.         foreach ($intervalos as $intervalo) {
  287.             $inicio $intervalo[0];
  288.             $fim $intervalo[1];
  289.             if ($horaAtual >= $inicio && $horaAtual <= $fim) {
  290.                 return true;
  291.             }
  292.         }
  293.     
  294.         return false;
  295.         
  296.     }
  297.     
  298.     /**
  299.      * @Route("/app-externo/pedidos-pendentes-cadastro", name="pedidos_pendentes_cadastro")
  300.      */
  301.     public function pedidosPendentesCadastro(Request $requestHttpClientInterface $client): Response
  302.     {
  303.         $pedidosPendentes = [];
  304.         
  305.         if($this->dentroIntervaloAbrirPedidosPendentes()) {
  306.             if($this->isAdmin() || $this->getIsVendedor()) {
  307.     
  308.                 $pedidosImportados $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtualWithData($this->getUser()->getEmail());
  309.                 foreach ($pedidosImportados as $pedidoImportado) {
  310.                     $pedidoEncontado $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoImportado['pedido']]);
  311.                     if(!$pedidoEncontado instanceof EntregaPedido){
  312.                         $pedidosPendentes[] = ['pedido'=>$pedidoImportado['pedido']];
  313.                     }
  314.                 }
  315.                 
  316.             }
  317.             
  318.         }
  319.         
  320.         return new JsonResponse($pedidosPendentes200);
  321.     }
  322.     
  323.     /**
  324.      * @Route("/app-externo/conta-estoque", name="app_externo_conta_sku")
  325.      */
  326.     public function contaEstoque(Request $requestHttpClientInterface $client): Response
  327.     {
  328.         if($request->get('sku')){
  329.             
  330.             $sku $request->get('sku');
  331.             
  332.             // Pega todos os pedidos à entregar
  333.             $pedidosAEntregar $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosContagemEstoque();
  334.             
  335.             $totalReservados 0;
  336.             $strInfo '';
  337.             
  338.             foreach ($pedidosAEntregar as $pedido) {
  339.                 $pedidoFeed $this->contaOcorrenciasDeProdutoNoPedido($pedido$sku);
  340.                 $totalReservados +=$pedidoFeed['estoqueReal'];
  341.                 $strInfo .=$pedidoFeed['info'];
  342.                 
  343.             }
  344.             $script 'const valorContado = prompt("Informe o total contado do produto no estoque físico: '.$sku.'");';
  345.             $script .= 'const valorReservados = '.$totalReservados.';console.log("valorReservados: " + valorReservados);console.log("valorContado: " + valorContado);console.log("Total de pedidos: '.count($pedidosAEntregar).'\n\n'.$strInfo.'");';
  346.             $script .= 'var valorCorreto = valorContado-valorReservados;';
  347.             $script .= 'const info = "'.$strInfo.'\n\n";';
  348.             $script .= 'alert("Alimentar no Bling: " + valorCorreto + "\n\n" + info);window.close();';
  349.             
  350.             echo '<script>'.$script.'</script>';
  351.             
  352.         }
  353.         
  354.         exit;
  355.         
  356.     }
  357.     
  358.     private function contaOcorrenciasDeProdutoNoPedido($pedido$sku) {
  359.         
  360.         $totalReservados 0;
  361.         
  362.         $itens $pedido->getItensPedido();
  363.         if($itens==null || $itens=='') {
  364.             return ['estoqueReal'=>$totalReservados,'info'=>''];
  365.         }
  366.         
  367.         $itens json_decode($itens);
  368.         $infoStr '';
  369.         
  370.         $status $pedido->getStatus();
  371.         
  372.         $status strtoupper($status);
  373.             
  374.         switch ($status) {
  375.             
  376.             case 'PENDENTE':
  377.                 $status 'À Entregar';
  378.                 break;
  379.                 
  380.             case 'RECEBIDO':
  381.                 $status 'Em Andamento';
  382.                 break;
  383.                 
  384.             case 'TRANSITO':
  385.                 $status 'Em Trânsito';
  386.                 break;
  387.             
  388.             case 'ENTREGUE':
  389.                 $status 'À Finalizar';
  390.                 break;
  391.                 
  392.             case 'PENDENTE_ADMIN':
  393.                 $status 'Pendente';
  394.                 break;
  395.                 
  396.             case 'COTACAO':
  397.                 $status 'Cotação';
  398.                 break;
  399.                 
  400.             case 'AGUARDANDO_PAGAMENTO':
  401.                 $status 'Aguardando Pagamento';
  402.                 break;
  403.                 
  404.             case 'ACEITO':
  405.                 $status 'Aceito';
  406.                 break;
  407.                 
  408.             default:
  409.                 // code...
  410.                 break;
  411.         }
  412.         
  413.         foreach ($itens as $item) {
  414.             if($item->codigo==$sku) {
  415.                 if($status!='Em Trânsito' && $status!='Aceito' && $status!='À Finalizar'){
  416.                     $totalReservados += $item->quantidade;
  417.                 }
  418.                 $infoStr .= 'Pedido: ' $pedido->getPedido() . ' - Status: '.$status.' - Qtd: ' $item->quantidade '\n'
  419.             }
  420.         }
  421.         
  422.         return ['estoqueReal'=>$totalReservados,'info'=>$infoStr];
  423.     }
  424.     
  425.     /**
  426.      * @Route("/app-externo/print-os/{id}", name="print_os", methods={"GET"})
  427.      */
  428.     public function printOS(Request $requestHttpClientInterface $client$id): Response
  429.     {
  430.         $os $this->getDoctrine()->getRepository(OrdemServico::class)->find(intval($id));
  431.         
  432.         if(!$os instanceof OrdemServico) {
  433.             return new JsonResponse([], 400);
  434.         }
  435.         
  436.         $css '
  437.             body,html{
  438.                 margin-top:10px;
  439.                 margin-bottom:10px;
  440.             }
  441.             .page_break { page-break-before: always; }
  442.             .th_header{
  443.                 text-align:center;
  444.                 font-weight:bold;
  445.             }
  446.         ';
  447.         
  448.         $img '<div style="text-align:center;"><img src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD//gA7Q1JFQVRPUjogZ2QtanBlZyB2MS4wICh1c2luZyBJSkcgSlBFRyB2NjIpLCBxdWFsaXR5ID0gODAK/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgAaADwAwEiAAIRAQMRAf/EAB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAEEQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEBAQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXETIjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFlaY2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A+qaKKr6ldLY6ddXcg+SCJpW+ign+lAFiivzw8QfGbx5rGrXF4PEeoWaSMSlvaTGKONc8KAPT1PNZ3/C0/Hn/AEN2t/8AgY/+NAH6QUma/OD/AIWn48/6G7W//Ax/8a674V/Gbxlp/jfSY9S1y81LT7m5jguILyQyDYzBSQTyCM549KAPvKiis3xLeS6d4d1W9t9vnW1rLNHuGRuVCRn8RQBpUV8NW37TfxAinV5W0qdAeY3tcBvxDA17t8Hv2gNJ8cX0WkaxbrpGsyYEQ37oZ29FJ5B9j+ZoA9vooqtqN9a6bYz3l/cR29rAheSWRtqoo6kmgCzRXzP49/alsbG6ktfBumDUdhx9suyUib/dQYYj6kV50f2ofHhn3iDRAmf9X9mfH/oef1oA+3aK+X/A37VNvc3Mdv4z0hbRGODd2JZlX3ZDk4+hP0r6T0fVLLWdNg1DS7qK7sp13RzRNlWFAF2iuJ+NHiS/8JfDTWtb0cxLfWqRmIypuUFpFU5HfgmvJ/2bfi54o8f+L9Q03xDJZvbQ2RnTyYAhDB1HXPTDGgD6OoorxL9pv4j6/wDDzT9Bl8OPbI97LMspmi8zhQpGPT7xoA9toryf9nDxzrPj7wVean4gaB7qK+eBTDHsG0IhGR9WNesUAFFcj8RPiF4f8AaYt34hu9jyA+RbRjdLMR2Vf6nA96+a/En7VmuzzuvhzRNPtLfPyvdlppMevylQP1oA+wqK+KtM/am8ZwTg39ho13DnlRE8bfgQ/wDQ17n8K/j34b8c3MWnXQbR9Yk4SCdgUlPoj+vscH0zQB7FRRRQAUUUUAFcn8WL3+z/AIZ+KLnO3Zp0+D7lCP611leX/tMXv2L4KeJCDhpkihH/AAKVAf0zQB+fdFFFABVjT5jb39tMpwY5FcH0wQar0UAfqbYzC5srecHIljVwfqM1meN/+RM17/sH3H/otqqfDW8/tD4eeGbvOTNptu5Pv5a5/Wrfjf8A5EzXv+wfcf8AotqAPz++Cfh/T/FPxL0fRtYjaWxujIsiqxU8RsRgj3ArV+N/w1ufhd4qt0tbiWbTbrM1jcnh1KkZViP4lJHI65Bpf2aP+S1eHP8Afk/9FtXqv7bOu2U83h7Q4ZEkvrcyXMwByY1YAKD9cE/hQB7f8B/F0vjX4ZaVqd426/QNbXJ9ZEON34jB/GvmT9p/4pXHinxJceG9JuGXQdOk2PsOBczD7zH1VTkAexPpXp37Pc1z4b/Zs17WTlCBeXcBP+wmAf8AvpDXz18CtBh8VfFrQrK/US25nNzMrc7wgLkH6kUAeq/BX9nMa7plvrfjh7i2tZ13wWEJ2SOp6M7fwg+g59xXua/Av4crbeR/wjNuRjG8yyb/AM91elAYAA4ApaAPk/4w/s2Q2OmT6v4Be4kMKl5dNmbeWUdTG3Un/ZOc9j2rgP2cvijc+BvFEOl6lOx8PX8gjmRycW7ngSD05wD7fSvu81+f37S3h238N/FzVYrJFjtrsJeIijAUuPmx/wACDH8aAPrH9pc5+CHiX/rnD/6OSvAP2Kv+Sjav/wBgxv8A0bHXqHjrVZdb/ZD/ALQuGLTTada+YxPJZZY1J/MV5f8AsVf8lG1f/sGN/wCjY6APs+vmD9uL/kE+Ev8Arvcf+gx19P18wftxf8gnwl/13uP/AEGOgDf/AGLf+SZal/2FH/8ARcdevfEDxVZ+C/COo67qHMVrHlUzzI54VB9SQK8h/Yt/5JlqX/YUf/0XHWR+25q0sHh3w3pUbER3VxLPIB38tVA/9DP5UAfO9zN4m+LvxBzh73Vr+TCIDhIU9B/dRR/nNfVHgX9mrwlo9jE/iQS61qJGZNzmOFT6Kq4OPcn8q5z9ijw7bx6FrfiKRFa7mnFnGxHKIoDMB9Swz/uivpqgDyvW/gF8O9UtGhTQxYuRgTWkrI6+/JIP4g18o/Gr4San8MtSinjme80Wd8W94BtZGHOxwOjeh6HH4V+gVcr8UfD1v4p+H+uaVdIredau0ZI+5IoJRh9GAoA8z/Zb+KM3jLQpdC1ybzNa01AVlY/NcQ5wGP8AtKSAfXIPrXu1fnx+zjqsukfGbw95bELczG0kAPVXBGPzwfwr7/v7600+3M9/dQWsAIBkmkCKCegyTigCxRWTaeJNDvLhLe01nTZ53OEjiukZmPsAcmtagArwP9sLWLaP4Yf2fHdQtczX8SvCsgLgAM3I6joK95lbZEzegJr4D+HXhC4+L3irxb9ru2GrG1kvYZXbgzeauA3sQSPbI9KAPKqKkuIXt7iSGZdssbFGHoQcEVHQAUUVe0TTLnWtYstMsVDXV5MkEQJwNzEAZPpzQB97/s5axbah8I/DUC3MLXUNsYmiEgLqEcryOvYV2njf/kTNf/7B9x/6Lavjyz8PyfCr9onwrpOm3ckjsbSO4fOBIZQFkGP7pJOB9K+w/G3/ACJev/8AXhcf+i2oA/Nvwzr2oeGdat9W0afyL+33eXJtDbcqVJweOhNdl8OvAXib4s+Kmmka5kgklD32qXGWCgnnk/eb0A/QVH8ANLsda+LegWOq2kN5ZyyPvhmXcjYRiMjvyBX6E2Nla6fax21hbw21vGMJFCgRVHsBwKAOX1zwpbQfCvUvC2jw7LcaXLZwJ3yYyBn3J5+pr4d+BGvQ+Fvi1oV7qDeVb+cbaZm42BwUyfYEiv0SxXw9+078Lrjwp4nuPEGlW7NoGoyeYSi8W0x5ZT6AnJB98dqAPuAEEAg8UtfJHwV/aNj0nTbfRPHgnlhgASHUowXcKOgkXqcf3hz7d69yX42fDtoPO/4SmyC4zghw35YzQB6Ia+AP2mPENv4j+Luqy2TiS3s1SzV1OQxQfNj/AIEWH4V6v8Yv2k7afTp9J+H/AJxkmBSTU5FKbFPXy1POf9o4x2HevNf2d/hfdeO/FUOpajA48PWMokuJHHE7jkRj1ycZ9vqKAPc/HGlS6L+yCNPuFKzRadal1PUM0qMR+ZrzD9ir/ko2r/8AYMb/ANGx17/+0uMfBDxKB08uH/0clfNv7JGvaT4e8eanc65qNpp9vJp7RrJcyiNS3mIcAnvgGgD7ir5g/bi/5BPhL/rvcf8AoMde5QfEnwXPNHFD4p0V5ZGCKq3aEsTwAOa8N/bi/wCQT4S/673H/oMdAG/+xb/yTLUv+wo//ouOsf8Abc0qWfw94b1WNCY7W4lgkPp5iqR/6Aah/ZL8Y+HPD/w91C11zXNO0+4fUXkWO5nWNivloMgE9Mg16z4pu/BnxR8Pah4Vtdf0u8uLyImJYLhJHR15VwAc8EA/TNAHlf7FHiG3k0DW/DzuFu4LgXiKTy6MApI+hUZ/3hX0zX5w/wDFT/CH4g5Aey1awkOMg+XPH/7MjD/ORX1d4E/aQ8H63YRDX5m0TUQoEiSqzxMe5VwOnscfjQB7hXL/ABP8QW3hfwDrmq3bhRDauIwT9+RgQij6sRXMaz8d/h5pdq0p8QRXbAZWK1jaRm9umB+JFfKPxt+L+pfEy/itbeF7LQ4HzBaBtzSN03vjqfQds9+tAFT9nLS5dX+M3h0RqWFtMbuQ+ioCc/ngfjX37qenWOq2ptdTs7e8tiQTFcRrIhI6HBGK8Q/ZY+F8/g/RZtf1yAxazqSBY4XGGt4M5wfRmIBI7YHvXvVAHlnjnw3oej+JfAM+k6Pp1jO2uqjSW1skbFfs85xlQOMgce1ep1wPxO/5Dvw//wCw+v8A6TT131AEdz/x7y/7p/lXwJ8DPiBZfDnWPEeq3kT3E8ti0FrAvHmSmRSAT2AAJJ9q+/XAZSp5BGDXxV8R/wBnfxba6jquqaDY2M+ntcM0FjZzM0qRknHDAZwMZ5JoA8Iu53urqa4lx5krtI2PUnJqGtjX/DGu+HpvK1zSL+wfGR9ogZAR7EjBrHoAK0vDWrS6D4h03VrdFeWxuY7hUboxRgcH64rNroPD3gzxL4jDHQtC1G+RRkvDAzKP+BYxQB6jrfjKw8eftD+D9d0xZI4pp7BZIpBzHIrjcue+D3719oeJbOXUPDmq2VsAZ7i0lhjDHA3MhAyfqa+Xvgp8AvEmi+L9E8QeJrbThZwnzmtXnbzonAyhwoxuDYOM4r6zFAHyV8Ffgd418KfEvR9Z1m0tI7C1ZzIyXSuRlGAwB7kV9bUUUAFVtSsLTU7Cey1C2iubSdSkkMqhlcHsQas0UAfMvj39lmyvLmS78GaoLAMc/YrtS8Y/3XHIHsQfrXnLfsw+PRceWH0cx/8APT7U2Py25r7gqO4aRYZDCivKFJRWOAT2BPagD5g8DfsrwwXMdz4z1dblFOTZ2SlVb/ekPOPYAfWvpXRtKsdE0yDT9KtIbSygXbHDEoVVH+e9ReHrG40/S4ob67e8vCWkmmYnBdjkhR2UZwB2AFadAHEfGrw5qHiz4Za3omjJG9/dJGIlkcIpIkVjyenANfJH/DNvxF/58LH/AMDUr7uooA+H9D/Z0+INpren3E9jYrFDcRyOReIcKGBNe4/tPfDrxB8QdP0CLw1BBM9nLM0olmEeAwUDGev3TXt9FAHwj/wzb8Rf+fCx/wDA1K9G+APwX8Y+DPiTZ6zr1raRWMUMyM0dyrnLIQOB9a+qKKAOP+I3w78P/EDTRa6/aBpYwfJuovlmhJ/ut6ex4NfNfiT9lXXre4c+HtasL23Jyq3StC4HocbgfrxX2JWF4o0jUNWbTDputXGlC1u0uJhDGH+0xjrE2egPrQB8g6Z+y943uJwt7caTZxZ5cztIcewC/wCFe6fCv9n/AMO+CbmLUb+Q61rEfzJNNGFiib1RMnn3JPtivZhS0AIKWiigDgvid/yHfh//ANh9f/Saeu9rgvid/wAh34f/APYfX/0mnrvaACiis3xFrVh4d0S81bVpxBY2qb5ZME4GcDgdSSQKALtzbw3MZjuIo5UPVXUMD+Brwb9qjQND0r4U3l5p+h6Vb3klzDF9ojtEWRQWycMBkE4x9Ca0dX1z4q+NyU8GaTD4W0hx8t/qpH2h19RHhtuR7H615z8TvgX4oXwdqmu6z40u9c1Cyi+0G1kVthUcvgljjAyRx2oA6j9kPSNI1X4bz3F/o+mXF3b6hJElxJao0m3ajDLEZ6sa+iIY44UCRIqIOiqMAV8efBf4J6/rfgy28S6b4su9Aurp2aCKFWwyA4DMQw6kHseMV6npl18YvA8qrrVpaeNNIXgyWbBLpV9QCBuPtg/WgD3OsD4gSz2/gXxFPaTPBcxadcSRSocMjLGxBB9iKk8H+JtP8W6HFqmkvIYHZo2SVCjxOpwyMp6MDwah+Iv/ACT7xP8A9gu6/wDRTUAZfh/T5/FWhafqmvS30K3NtHJHZQ3LwiIFQcuUILMc5OTgdAOpNG/ur/wp4i07Q9OluLq11sSR2jXUhmNlKg3MSzHcyFCSASeVxnB46/wt/wAizpH/AF5w/wDoArnPGX/JQvAX/Xxd/wDpO1AFy68E2l1ATLqetC/xkXiahKjBv7wQME/4Dtx7U74e6te6jpV1a6w6yatpd1JY3UirtEpXBWTHbcjI2PUmuprifAX/ACNXj4dv7Wj/APSSCgDtXYIhZiAoGST2FcHoUV146g/ti/u7y00KVj9gsraVoGljBwJpXUhjuxkKCAFIzk112v20t5oWo21ucTTW0kaH0YqQKxfhddRXfw88PPANoSyjhZehR0Gx1I7EMpB+lAFbUfCt1pkD3fhHULyC/jG5ba7upJ7e4x/AwkLFc9Ny4I9+lbnhXW4PEfh+z1W1R40uEy0T/eicEhkb3VgQfpWo7KqlmICgZJPYVxnwhzJ4Qa8UEQX19d3duCMZieZyh+hGD+NAFvx3dXOkJpuuQzSLZ2NwBfRA/K9vJ8jMR/sEq+fRW9a6kHIyKhvrWG+sp7S6jElvPG0UiN0ZSMEflXIeGtbOkeD9Qi1eR5Lrw+XtJj1eYIAYmHqXRk/EkUAXY7q51Tx7JDbzSJpukQYnCH5ZrmUZCn12Jg49ZB6V1DEKCTwB1NYfgvS5dL0KMX2DqN07Xd4w7zSHcwHsOFHsorS1aKSbS7yKA4leF1Q+5UgUAclpUVx42STU7y8urbQndlsrS1laFpkBI86R1Ib5sZVQQMYzknhmvaFP4aspda8NXl+Hs1M09hPdSTxXUS8soDlij4B2lcc4zkVjfCzwxY6j8PNAlXU9djlS0SCaKPU5lEUqDY6bQeMMpGO1dPN4FsZonil1TxA8bqVZTqs2CD1H3qAOmsrmK9s4Lq3bdDPGsqN6qwyD+RrmPiHe3NkPDZtJ5IfO1u1hk2HG9G3ZU+xxXSaVYwaZptpYWisttawpBEGYsQigKASeTwK5T4n/AHfCv/YftP5tQB2tcT4vvpbjxjoHhxryWxsr+G4uJZIX8uScxbMQq45XIcscYOE47121Y/ibw7pfiWxS11e381Y3EsTo7RyQuOjo6kMpHqDQBX03wrYaZqEd3Yz6lGy5DRvfzSxyZGPmV2I98jBroK4Fp9Y8G6zpNveajLq+gajcLYo9yq/abWVgdmXUDzEJGORuBI5Nd9QBwXxO/wCQ78P/APsPr/6TT13tcF8T/wDkO/D/AP7D6/8ApNPXe0AFeOfH/wCHHin4gNpUXh3XIbKwiyt1azSOiOSQQ/yg7sY6GvY6KAK+nQy29hbw3ExnmjjVHlIxvYDBbHbPWub+K+pS6T8O9duoLU3kv2fyVgHV/MIj/wDZq6yq+oSLDYXEsiCRY42coejYGcfpQB5/+z5dXcnwu0uz1CwewutMLafJDIMNuj4JI7HNejOCVIBwfX0rG8FawniHwlpOtR24thqNsl15QOdhdQxGe/XrW3QB4r8HPhn4t8GeN9c1HWfEEV3o940rpbRO58x3fd5jKQFQ8npnrXrPiPTv7Y8P6nphk8r7bay23mbc7N6Fc474zWjRQBV0q1+w6ZZ2e/f9nhSLdjG7aoGcfhWbrOhf2l4h0HU/P8v+y5JpPL258zfGUxnPGM5rcooAKxNA0P8AsnVdfvPP83+1btbrZtx5eIY49uc8/wCrz+NbdFAAa5OTw1e6Zqd3f+Fr6K1W7fzbixuYjJbvIesi4IZGPfGQeuM811lFAHG32ga74hjNp4j1G0g0p+JrTTUdWuB3V5WOQp7hQCfWuughjt4Y4YEWOKNQqIowFA4AA9KkooAK5XV/CS6h4pttUF40VriP7ZZhAVumiYtCSc8bWbPvhQeldVRQAUHmiigDjrjwtf6bq13qPhHUIbI3knnXVjdRGW2mk7yDBDIx7kHB6kZ5qysHi+4wk97otkmfmeC3kmf8NzAD8Qa6iigBBwBnk+tYvifQ/wC3BpQ8/wAn7DqEN993dv2Z+XrxnPWtuigArE1yDXmuYp9CvrGNFXa9teW7MrnP3g6sCp7dCK26KAOUTQdT1XU7C88S3do8VhL9ot7OzjZU83BAd2YksQCcAADnPOBXV0UUAcD8Tv8AkOfD/wD7D6/+k09d9XA/E7/kO/D/AP7D6/8ApNPXfUAFFFFABUV3CLm1mgYkLKhQkdQCMUUUAee6L8O9Z0bSbTTNN8e63DZWkSwwx/ZbVtiKMAZMeTx61d/4Q7xJ/wBFC1v/AMA7T/41RRQAf8Id4k/6KFrX/gJaf/GqP+EO8Sf9FC1v/wAA7T/41RRQAf8ACHeJP+iha3/4B2n/AMao/wCEO8Sf9FC1v/wEtP8A41RRQAf8Id4k/wCiha3/AOAdp/8AGqP+EO8Sf9FC1v8A8A7T/wCNUUUAH/CHeJP+iha3/wCAdp/8ao/4Q7xJ/wBFC1v/AMA7T/41RRQAf8Id4k/6KFrf/gHaf/GqP+EO8Sf9FC1v/wAA7T/41RRQAf8ACHeJP+iha3/4B2n/AMao/wCEO8Sf9FC1v/wDtP8A41RRQAf8Id4k/wCiha3/AOAdp/8AGqP+EO8Sf9FC1v8A8A7T/wCNUUUAH/CHeJP+iha3/wCAdp/8ao/4Q7xJ/wBFC1v/AMA7T/41RRQAf8Id4k/6KFrf/gHaf/GqP+EO8Sf9FC1v/wAA7T/41RRQAf8ACHeJP+iha3/4B2n/AMao/wCEO8Sf9FC1v/wDtP8A41RRQAf8Id4k/wCiha3/AOAlp/8AGqP+EO8Sf9FC1v8A8A7T/wCNUUUARx+Ab+bWtIv9Z8X6tqiaZc/a4beWC3jQybGTJKID0c9674UUUAf/2Q==" style="max-height: 112px; max-width: 130px;" class="center-image img-responsive"></div>';
  449.             
  450.         $body $img '<h4 style="text-align:center;font-size:20px;padding-top:3px;margin-bottom:10px;">POLLO MÓVEIS PARA ESCRITÓRIO</h4>
  451.                 <strong style="text-align:center;padding-bottom:16px;display:block;">Telefone:(62)3233-7424</strong><hr/><br/><strong style="text-align:center;padding-bottom:16px;display:block; color:blue;">OS Nª. '.str_pad($os->getId(), 4"0"STR_PAD_LEFT).' Criada em: '.$os->getCreatedAt()->format('d/m/d às H:i').'</strong>';
  452.                 
  453.         $body .= '<div>
  454.         
  455.             <strong style="text-align:center;padding-bottom:16px;display:block;">Descrição da OS</strong>
  456.             
  457.             <div>'.nl2br($os->getDescricao()).'</div>
  458.             
  459.         </div>';
  460.         
  461.         $htmlBase '<!DOCTYPE html>
  462.         <html>
  463.         <head>
  464.           <title>Ordem de serviço - Pollo Móveis</title>
  465.           <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  466.           <style>'.$css.'</style>
  467.         </head>
  468.         <body>
  469.           '.$body.'
  470.         </body>
  471.         </html>';
  472.         
  473.         
  474.         if (get_magic_quotes_gpc()) {
  475.             $htmlBase stripslashes($htmlBase);
  476.         }
  477.         
  478.         $options = new Options();
  479.         $options->set('defaultFont''Helvetica');
  480.         $options->set('isHtml5ParserEnabled'true);
  481.         $dompdf = new Dompdf($options);
  482.         $dompdf->loadHtml($htmlBase);
  483.         $dompdf->setPaper('A4');
  484.         
  485.         // Renderize o PDF (processa HTML em PDF)
  486.         $dompdf->render();
  487.                 
  488.         // Obtém o conteúdo do PDF gerado
  489.         $output $dompdf->output();
  490.         // Configuração da resposta HTTP para exibir o PDF no navegador
  491.         header('Content-Type: application/pdf');
  492.         header('Content-Disposition: inline; filename="relatorio-credito-debito-pollo-distribuidora.pdf"');
  493.         header('Cache-Control: private, max-age=0, must-revalidate');
  494.         header('Pragma: public');
  495.         header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
  496.         header('Last-Modified: ' gmdate('D, d M Y H:i:s') . ' GMT');
  497.         
  498.         // Envia o conteúdo do PDF para o navegador
  499.         echo $output;
  500.         
  501.         exit;
  502.         
  503.     }
  504.         
  505.     /**
  506.      * @Route("/app-externo/add-os", name="add_os", methods={"POST"})
  507.      */
  508.     public function addOS(Request $requestHttpClientInterface $client): Response
  509.     {
  510.         $data json_decode($request->getContent(), false);
  511.         
  512.         $os = new OrdemServico();
  513.         $os->setDescricao($data->textNewOs);
  514.         $os->setStatus('pendente');
  515.         $os->setCreatedAt(new \DateTime());
  516.         $os->setNumero(mt_rand(1000000099999999));
  517.         
  518.         $this->getDoctrine()->getManager()->persist($os);
  519.         $this->getDoctrine()->getManager()->flush();
  520.         
  521.         return new JsonResponse([], 200);
  522.     }
  523.     
  524.     /**
  525.      * @Route("/app-externo/apaga-os", name="apaga_os", methods={"POST"})
  526.      */
  527.     public function apagaOS(Request $requestHttpClientInterface $client): Response
  528.     {
  529.         $data json_decode($request->getContent(), false);
  530.         
  531.         $os $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
  532.         
  533.         if(!$os instanceof OrdemServico) {
  534.             return new JsonResponse([], 400);
  535.         }
  536.         
  537.         $os->setDeletedAt(new \DateTime());
  538.         $this->getDoctrine()->getManager()->flush();
  539.         
  540.         return new JsonResponse([], 200);
  541.         
  542.     }
  543.     
  544.     /**
  545.      * @Route("/app-externo/baixa-os", name="baixa_os", methods={"POST"})
  546.      */
  547.     public function baixaOS(Request $requestHttpClientInterface $client): Response
  548.     {
  549.         $data json_decode($request->getContent(), false);
  550.         
  551.         $os $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
  552.         
  553.         if(!$os instanceof OrdemServico) {
  554.             return new JsonResponse([], 400);
  555.         }
  556.         
  557.         $os->setStatus('baixado');
  558.         $os->setBaixadoPor($this->getUser());
  559.         $os->setBaixadoAt(new \DateTime());
  560.         
  561.         $this->getDoctrine()->getManager()->flush();
  562.         
  563.         return new JsonResponse([], 200);
  564.         
  565.     }
  566.     
  567.     /**
  568.      * @Route("/app-externo/aceita-os", name="aceita_os", methods={"POST"})
  569.      */
  570.     public function aceitaOS(Request $requestHttpClientInterface $client): Response
  571.     {
  572.         $data json_decode($request->getContent(), false);
  573.         
  574.         $os $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
  575.         
  576.         if(!$os instanceof OrdemServico) {
  577.             return new JsonResponse([], 400);
  578.         }
  579.         
  580.         // if(($os->getSolicitarMontagem() && $os->getSolicitarMontagemSaoJose()) || ($os->getSolicitarMontagemSaoJose() && $os->solicitarSeparacaoSaoJose())){
  581.             
  582.         // } else {
  583.         //     return new JsonResponse([], 400);
  584.         // }
  585.         
  586.         $os->setStatus('aceito');
  587.         $os->setAceitoPor($this->getUser());
  588.         $os->setAceitoAt(new \DateTime());
  589.         
  590.         $this->getDoctrine()->getManager()->flush();
  591.         
  592.         return new JsonResponse([], 200);
  593.         
  594.     }
  595.     
  596.     /**
  597.      * @Route("/app-externo/edit-os", name="edit_os", methods={"POST"})
  598.      */
  599.     public function editOS(Request $requestHttpClientInterface $client): Response
  600.     {
  601.         $data json_decode($request->getContent(), false);
  602.         
  603.         $os $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
  604.         
  605.         if(!$os instanceof OrdemServico) {
  606.             return new JsonResponse([], 400);
  607.         }
  608.         
  609.         $os->setDescricao($data->texto);
  610.         $this->getDoctrine()->getManager()->flush();
  611.         
  612.         return new JsonResponse([], 200);
  613.         
  614.     }
  615.     
  616.     /**
  617.      * @Route("/app-externo/lista-os", name="lista_os", methods={"GET"})
  618.      */
  619.     public function listaOS(Request $requestHttpClientInterface $client): Response
  620.     {
  621.         $data = [];
  622.         
  623.         $oss $this->getDoctrine()->getRepository(OrdemServico::class)->findBy(['deletedAt'=>null], ['createdAt'=>'desc']);
  624.         foreach ($oss as $os) {
  625.             if($os->getStatus()=='baixado'){
  626.                 continue;
  627.             }
  628.             $data[] = [
  629.                 'id' => $os->getId(),
  630.                 'numero' => str_pad($os->getId(), 4"0"STR_PAD_LEFT),
  631.                 'texto' => $os->getDescricao(),
  632.                 'status' => $os->getStatus(),
  633.                 'createdAt' => $os->getCreatedAt()->format('d/m/Y às H:i'),
  634.                 'aceitoAt' => ($os->getAceitoAt()) ? $os->getAceitoAt()->format('d/m/Y H:i') : '',
  635.                 'aceitoPor' => ($os->getAceitoPor()) ? $os->getAceitoPor()->getEmail() : ''
  636.             ];
  637.         }
  638.         
  639.         return new JsonResponse($data200);
  640.     }
  641.     
  642.     /**
  643.      * @Route("/app-externo/update-obs-emergencial", name="update_obs_emergencial", methods={"POST"})
  644.      */
  645.     public function updateObsEmergencial(Request $requestHttpClientInterface $client): Response
  646.     {
  647.         $data json_decode($request->getContent(), false);
  648.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
  649.         
  650.         if(!$pedido instanceof EntregaPedido) {
  651.             return new JsonResponse([], 400);
  652.         }
  653.         
  654.         $pedido->setObsEmergencial($data->obsEmergencial);
  655.         $this->getDoctrine()->getManager()->flush();
  656.         
  657.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  658.         
  659.     }
  660.     /**
  661.      * @Route("/app-externo/deletar_pedido_customizado", name="deletar_pedido_customizado", methods={"POST"})
  662.      */
  663.     public function deleteItensPedido(Request $requestHttpClientInterface $client): Response
  664.     {
  665.         $data json_decode($request->getContent(), false);
  666.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
  667.         
  668.         if(!$pedido instanceof EntregaPedido){
  669.             return new JsonResponse([], 400);
  670.         }
  671.         
  672.         $pedido->setRazaoSocialCustomizado(null);
  673.         $pedido->setEnderecoSocialCustomizado(null);
  674.         $pedido->setItensPedidoCustomizado(null);
  675.         $pedido->setFreteCustomizado(null);
  676.         $pedido->setClienteCustomizado(null);
  677.         $pedido->setFormaPagamentoCustomizado(null);
  678.         $pedido->setVendedorCustomizado(null);
  679.         $pedido->setDesconto(null);
  680.         $this->getDoctrine()->getManager()->flush();
  681.         
  682.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  683.     }
  684.     
  685.     /**
  686.      * @Route("/app-externo/salvar_pedido_customizado", name="salvar_pedido_customizado", methods={"POST"})
  687.      */
  688.     public function saveItensPedido(Request $requestHttpClientInterface $client): Response
  689.     {
  690.         $data json_decode($request->getContent(), false);
  691.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
  692.         
  693.         if(!$pedido instanceof EntregaPedido){
  694.             return new JsonResponse([], 400);
  695.         }
  696.         
  697.         $itens $data->itensPedidoCustomizado;
  698.         $itensRecalculate = [];
  699.         foreach ($itens as $item) {
  700.             
  701.             if(strstr($item->valorunidade'R$')){
  702.                 $valor preg_replace("/[^0-9,.]/"""$item->valorunidade);
  703.                 $valor str_replace("."""$valor);
  704.                 $valor str_ireplace(',','.'$valor);
  705.             } else {
  706.                 $valor $item->valorunidade;
  707.             }
  708.             
  709.             $valorTotal $valor $item->quantidade;
  710.             $itensRecalculate[] = [
  711.                 'titulo' => $item->titulo,
  712.                 'codigo' => $item->codigo,
  713.                 'valorunidade' => number_format($valor2'.'''),
  714.                 'quantidade' => abs($item->quantidade),
  715.                 'valorTotal' => $valorTotal
  716.             ];
  717.             
  718.         }
  719.         
  720.         $valorFrete preg_replace("/[^0-9,.]/"""$data->freteCustomizado);
  721.         $valorFrete str_replace("."""$valorFrete);
  722.         $valorFrete str_ireplace(',','.'$valorFrete);
  723.         
  724.         $valorDesconto preg_replace("/[^0-9,.]/"""$data->desconto);
  725.         $valorDesconto str_replace("."""$valorDesconto);
  726.         $valorDesconto str_ireplace(',','.'$valorDesconto);
  727.             
  728.         $pedido->setRazaoSocialCustomizado($data->razaoSocialCustomizado);
  729.         $pedido->setEnderecoSocialCustomizado($data->enderecoSocialCustomizado);
  730.         $pedido->setItensPedidoCustomizado(json_encode($itensRecalculate));
  731.         $pedido->setFreteCustomizado($valorFrete);
  732.         $pedido->setClienteCustomizado($data->clienteCustomizado);
  733.         $pedido->setFormaPagamentoCustomizado($data->formaPagamentoCustomizado);
  734.         $pedido->setVendedorCustomizado($data->vendedorCustomizado);
  735.         $pedido->setDesconto($valorDesconto);
  736.         //$pedido->setDesconto($data->desconto);
  737.         
  738.         $this->getDoctrine()->getManager()->flush();
  739.         
  740.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  741.     }
  742.     
  743.     /**
  744.      * @Route("/app-externo/itens_pedido/{pedido}", name="itens_pedido", methods={"GET"})
  745.      */
  746.     public function getItensPedido(Request $requestHttpClientInterface $client$pedido): Response
  747.     {
  748.         $itens $this->getItensPedidoSingle($client$pedido); //44286
  749.         return new JsonResponse($itens200);
  750.     }
  751.     
  752.     private function getItensPedidoSingle($client$numero) {
  753.         
  754.         $itens = [];
  755.         
  756.         $response $client->request(
  757.             'GET',
  758.             SincronizacaoController::URL_API_BLING '/pedido/'.$numero.'/json/',
  759.             [
  760.                 'query' => [
  761.                     'apikey' => SincronizacaoController::KEY_API_POLLO
  762.                 ]
  763.             ]
  764.         );
  765.         $statusCode $response->getStatusCode();
  766.         
  767.         if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
  768.             $content $response->toArray();
  769.             if(isset($content['retorno'])) {
  770.                 if(isset($content['retorno']['pedidos'])) {
  771.                     if(count($content['retorno']['pedidos']) > 0) {
  772.                         if(isset($content['retorno']['pedidos'][0])) {
  773.                             
  774.                             $pedido $content['retorno']['pedidos'][0]['pedido'];
  775.                             
  776.                             if(!empty($pedido['itens'])){
  777.                                 foreach ($pedido['itens'] as $item) {
  778.                                     
  779.                                     $item $item['item'];
  780.                                     $valorTotal $item['valorunidade'] * $item['quantidade'];
  781.                                     $itens[] = [
  782.                                         'titulo' => $item['descricao'],
  783.                                         'codigo' => $item['codigo'],
  784.                                         'valorunidade' => number_format($item['valorunidade'], 2'.'''),
  785.                                         'quantidade' => abs($item['quantidade']),
  786.                                         'valorTotal' => $valorTotal
  787.                                     ];
  788.                                     
  789.                                 }
  790.                             }
  791.                             
  792.                         }
  793.                     }
  794.                 }
  795.             }
  796.         }
  797.         
  798.         return $itens;
  799.         
  800.     }
  801.     
  802.     /**
  803.      * @Route("/app-externo/salvar_info_geovair", name="salvar_info_geovair", methods={"POST"})
  804.      */
  805.     public function salvarInfoGeovair(Request $request): Response
  806.     {
  807.         $data json_decode($request->getContent(), false);
  808.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  809.         
  810.         if(!$pedido instanceof EntregaPedido){
  811.             return new JsonResponse([], 400);
  812.         }
  813.         
  814.         $estaPago = ($data->estaPago=='true') ? true false;
  815.         $emitirNf = ($data->emitirNf=='true') ? true false;
  816.         $emitirBoleto = ($data->emitirBoleto=='true') ? true false;
  817.         $receberEntregaGeovair = ($data->receberEntregaGeovair=='true') ? true false;
  818.         $pedido->setEnviarGeovair(new \DateTime());
  819.         $pedido->setGeovairFormaPagamento($data->formaPagamento);
  820.         $pedido->setGeovairEstaPago($estaPago);
  821.         $pedido->setGeovairEmitirNf($emitirNf);
  822.         $pedido->setGeovairEmitirBoleto($emitirBoleto);
  823.         $pedido->setGeovairReceberEntregaColeta($receberEntregaGeovair);
  824.         
  825.         $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  826.         
  827.         $messageBody "*Dar andamento no pedido: Nº $numeroPedido*\n*Conforme instruções.*\n\n";
  828.         
  829.         $messageBody .= 'Imprimir: *' $pedido->getTipoDocumento() . "*\n";
  830.         $messageBody .= 'Forma de pagamento: *' $pedido->getFormaPagamento() . "*\n";
  831.         $messageBody .= 'Está pago: *' $pedido->getEstaPago() . "\n";
  832.         $messageBody .= 'Receber na entrega: *' $pedido->getReceberNaEntrega() . "*\n";
  833.         $messageBody .= 'Meio de entrega: *' $pedido->getMeioEntrega() . "*\n";
  834.         $messageBody .= 'Montar Móveis: *' $pedido->getMontarMoveis() . "*\n";
  835.         $messageBody .= 'Embalagem: *' $pedido->getEmbalagem() . "*\n";
  836.         $messageBody .= 'Período da Entrega: *' $pedido->getPeriodoEntrega() . "*\n";
  837.         $messageBody .= 'Link Pedido: ' "https://app.moveispollo.com.br/pedido/$numeroPedido";
  838.         
  839.         $img 'https://polo.srvtmp.com.br/andamento.png?v=3';
  840.         $this->sendMensagemViaWhatsapp("img"'5562993602042'$messageBody$imgnullnull); // Geovair
  841.         $this->sendMensagemViaWhatsapp("img"'5562981352530'$messageBody$imgnullnull); // Mateus
  842.         $this->sendMensagemViaWhatsapp("img"'5562995698482'$messageBody$imgnullnull); // Samuel
  843.         //$this->sendMensagemViaWhatsapp("img", '5562983281823', $messageBody, $img, null, null); // Samuel
  844.         
  845.         $this->getDoctrine()->getManager()->flush();
  846.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  847.     }
  848.     
  849.     /**
  850.      * @Route("/app-externo/ids_produtos_bling", name="ids_produtos_bling", methods={"GET"})
  851.      */
  852.     public function idsProdutosBling(Request $request): Response
  853.     {
  854.         header("Access-Control-Allow-Origin: *");
  855.         header('Access-Control-Allow-Methods: GET, POST');
  856.         header('Access-Control-Allow-Headers: Content-Type, Authorization');
  857.         header('Access-Control-Allow-Credentials: true');
  858.         header('Content-Type: application/json');
  859.         
  860.         $produtosBling $this->getDoctrine()->getRepository(ProdutoBling::class)->findAll();
  861.         $ids = [];
  862.         foreach ($produtosBling as $prod) {
  863.             if($prod->getIdBling())
  864.                 $ids[] = ['id'=>$prod->getIdBling(), 'sku'=>$prod->getCodigo()];
  865.         }
  866.         
  867.         return new JsonResponse($ids200);
  868.     }
  869.     
  870. ###### V2
  871.     /**
  872.      * @Route("/app-externo/v2", name="app_externo_v2")
  873.      */
  874.     public function indexv2(Request $request): Response
  875.     {
  876.         
  877.         $abrePedidoParaCadastro 'false';
  878.         if($request->get('add_card')){
  879.             $abrePedidoParaCadastro 'true';
  880.         }
  881.         
  882.         $hoje = new \DateTime();
  883.         return $this->render('app_externo/index-v2.html.twig', [
  884.             'controller_name' => 'AppExternoController',
  885.             'usario' => $this->getUser()->getEmail(),
  886.             'isAdmin' => $this->getIsAdmin(),
  887.             'isEntregador' => $this->getIsEntregador(),
  888.             'isEntregadorAux' => $this->getIsEntregadorAux(),
  889.             'isVendedor' => $this->getIsVendedor(),
  890.             'isSeparador' => $this->getIsSeparador(),
  891.             'menuContextoCard' => $this->getMenuContextoCard(),
  892.             'dataHoje' => $hoje->format('Y-m-d'),
  893.             // 'faturamentoAtual' => __DIR__,
  894.             'faturamentoAtual' => number_format($this->getFaturamentoAtual(), 2',''.'),
  895.             'abreNovoPedido' => $abrePedidoParaCadastro,
  896.             'pedidoNovoParaAdd' => $request->get('add_card'),
  897.             'temAlgumValePendente' => $this->temAlgumValePendente()
  898.         ]);
  899.  
  900.     }
  901.     /**
  902.      * @Route("/crons", name="app_crons")
  903.      */
  904.     public function cronsPageAction(Request $request): Response
  905.     {
  906.         return $this->render('app_externo/index-crons.html.twig');
  907.     }
  908.     
  909.     /**
  910.      * @Route("/crons/execute/{acao}", name="app_crons_execute")
  911.      */
  912.     public function cronsExecuteAction(Request $requestKernelInterface $kernel$acao): Response
  913.     {
  914.         $acaoEncontrada false;
  915.         
  916.         if($acao=='credito_debito'){
  917.             
  918.             $acaoEncontrada true;
  919.             
  920.             $application = new Application($kernel);
  921.             $application->setAutoExit(false);
  922.     
  923.             $input = new ArrayInput([
  924.                 'command' => 'app:acoes-pedidos-diario',
  925.                 '--somentedrive' => 'sim'
  926.             ]);
  927.             
  928.         } else if($acao=='promocoes') {
  929.             
  930.             $acaoEncontrada true;
  931.             
  932.             $application = new Application($kernel);
  933.             $application->setAutoExit(false);
  934.     
  935.             $input = new ArrayInput([
  936.                 'command' => 'app:envia-promocao-agendada'
  937.             ]);
  938.         }
  939.         
  940.         if($acaoEncontrada){
  941.                 
  942.             // You can use NullOutput() if you don't need the output
  943.             $output = new BufferedOutput();
  944.             $application->run($input$output);
  945.             
  946.             // return the output, don't use if you used NullOutput()
  947.             $content $output->fetch();
  948.     
  949.             // return new Response(""), if you used NullOutput()
  950.             return new Response($content);
  951.             
  952.         }
  953.         
  954.         exit('Nenhum comando encontrado');
  955.     }
  956. ###### DRIVE
  957.     /**
  958.      * @Route("/app-externo/itens_pagos_drive", name="itens_pagos_drive", methods={"POST"})
  959.      */
  960.     public function itens_pagos_drive(Request $request): Response
  961.     {
  962.         $data json_decode($request->getContent(), false);
  963.         
  964.         foreach ($data->itens as $item) {
  965.             
  966.             $lancamento $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($item->id);
  967.             
  968.             if($lancamento instanceof LancamentoClienteDrive) {
  969.                 $lancamento->setIsCalcula($item->isCalcula);
  970.                 $lancamento->setIsPago($item->isPago);
  971.                 $this->getDoctrine()->getManager()->flush();
  972.             }
  973.             
  974.         }
  975.         
  976.         return new JsonResponse([], 200);
  977.     }
  978.     
  979.     /**
  980.      * @Route("/app-externo/drive", name="app_drive")
  981.      */
  982.     public function drivePageAction(Request $request): Response
  983.     {
  984.         $hoje = new \DateTime();
  985.         return $this->render('app_externo/drive-index.html.twig', [
  986.             'primeiro_dia_mes' => $hoje->format('Y') . '-'.$hoje->format('m').'-01',
  987.             'ultimo_dia_mes' => $hoje->format('Y-m-d'),
  988.             'mesAtualDrive' => $hoje->format('m')
  989.         ]);
  990.  
  991.     }
  992.     
  993.     /**
  994.      * @Route("/app-externo/pagamento-pedido/delete/{id}", name="pagamentos_pedido_delete", methods={"GET"})
  995.      */
  996.     public function deletePagamentoPedidoAction(Request $request$id)
  997.     {
  998.         $lancamento $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->find($id);
  999.         if(!$lancamento instanceof PagamentoPedidoCreditoDebito) {
  1000.             return new JsonResponse([], 400);
  1001.         }
  1002.         
  1003.         $this->getDoctrine()->getManager()->remove($lancamento);
  1004.         $this->getDoctrine()->getManager()->flush();
  1005.         
  1006.         return new JsonResponse([], 200);
  1007.         
  1008.     }
  1009.     /**
  1010.      * @Route("/app-externo/list-pagamento-pedido/{pedido}", name="pagamentos_pedidos", methods={"GET"})
  1011.      */
  1012.     public function clientesDriveLancamentosAction(Request $request$pedido)
  1013.     {
  1014.         $pedidoRequest $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($pedido);
  1015.         
  1016.         if(!$pedidoRequest instanceof LancamentoClienteDrive){
  1017.             return new JsonResponse([], 400);
  1018.         }
  1019.         
  1020.         $pagamentos $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->findBy(['pedido'=>$pedidoRequest],['pagoAt'=>'asc']);
  1021.         $pagamentosData = [];
  1022.         foreach ($pagamentos as $pagamento) {
  1023.             $pagamentosData[] = [
  1024.                 'id'        => $pagamento->getId(),
  1025.                 'valor'     => number_format($pagamento->getValor(), 2',''.'),
  1026.                 'obs'       => $pagamento->getObs(),
  1027.                 'tipo'      => $pagamento->getTipo(),
  1028.                 'data'      => $pagamento->getPagoAt()->format('d/m/Y'),
  1029.             ];
  1030.         }
  1031.         
  1032.         return new JsonResponse($pagamentosData200);
  1033.     }
  1034.     /**
  1035.      * @Route("/app-externo/add-pagamento-pedido", name="add_pagamento_pedido", methods={"POST"})
  1036.      */
  1037.     public function createPagamentoPedido(Request $request): JsonResponse
  1038.     {
  1039.         $entityManager $this->getDoctrine()->getManager();
  1040.         $data json_decode($request->getContent(), false);
  1041.         
  1042.         $pedido $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
  1043.         
  1044.         if(!$pedido instanceof LancamentoClienteDrive){
  1045.             return new JsonResponse([], 400);
  1046.         }
  1047.             
  1048.         $date = \DateTime::createFromFormat('Y-m-d'$data->data);
  1049.         
  1050.         $valor preg_replace("/[^0-9,.]/"""$data->valor);
  1051.         $valor str_replace("."""$valor);
  1052.         $valor str_ireplace(',','.'$valor);
  1053.         $pagamento = new PagamentoPedidoCreditoDebito();
  1054.         $pagamento->setTipo($data->tipo);
  1055.         $pagamento->setPedido($pedido);
  1056.         $pagamento->setValor($valor);
  1057.         $pagamento->setPagoAt($date);
  1058.         
  1059.         if(!empty($data->nota)){
  1060.             $pagamento->setNota($data->nota);
  1061.         }
  1062.         
  1063.         if(!empty($data->obs)){
  1064.             $pagamento->setObs($data->obs);
  1065.         }
  1066.         
  1067.         $pagamento->setCreatedAt(new \DateTime());
  1068.         $entityManager->persist($pagamento);
  1069.         $entityManager->flush();
  1070.         return new JsonResponse(['message' => 'Pagamento criado com sucesso'], 200);
  1071.     }
  1072.     
  1073.     /**
  1074.      * @Route("/app-externo/atualiza-valores-drive", name="atualiza_valores_drive", methods={"GET"})
  1075.      */
  1076.     public function atualizaValoresDrive(KernelInterface $kernel)
  1077.     {
  1078.         
  1079.         $application = new Application($kernel);
  1080.         $application->setAutoExit(false);
  1081.         $input = new ArrayInput([
  1082.             'command' => 'app:acoes-pedidos-diario',
  1083.             '--somentedrive' => 'sim'
  1084.         ]);
  1085.         // You can use NullOutput() if you don't need the output
  1086.         $output = new BufferedOutput();
  1087.         $application->run($input$output);
  1088.         
  1089.         // return the output, don't use if you used NullOutput()
  1090.         $content $output->fetch();
  1091.         // return new Response(""), if you used NullOutput()
  1092.         return new Response($content);
  1093.     }
  1094.     /**
  1095.      * @Route("/app-externo/credito-debito-pdf/{id}/{mes}/{zap}", name="clientes_drive_pdf", methods={"GET"})
  1096.      */
  1097.     public function clientesDriveRelatorioPdfAction(Request $request$id$mes$zap)
  1098.     {
  1099.         
  1100.         $cliente $this->getDoctrine()->getRepository(ClienteDrive::class)->find($id);
  1101.         
  1102.         if(!$cliente instanceof ClienteDrive) {
  1103.             exit();
  1104.         }
  1105.         
  1106.         // Obtém a data atual
  1107.         $dataAtual = new \DateTime();
  1108.         $dataFiltroInicial = new \DateTime($dataAtual->format('Y-m-01'));
  1109.         $dataFiltroFinal = new \DateTime($dataAtual->format('Y-m-t'));
  1110.         
  1111.         $arrContextOptions=array(
  1112.             "ssl"=>array(
  1113.                 "verify_peer"=>false,
  1114.                 "verify_peer_name"=>false,
  1115.             ),
  1116.         );
  1117.         
  1118.         $logo "https://pollodistribuidora.com.br/wp-content/uploads/2022/05/pollodistribuidora.png";
  1119.         $dataLogo file_get_contents($logofalsestream_context_create($arrContextOptions));
  1120.         $base64Logo 'data:image/jpeg;base64,' base64_encode($dataLogo);
  1121.                     
  1122.         $hoje = new \DateTime();
  1123.         $body "
  1124.         <div style='text-align:center;'><img src='$base64Logo'/></div>
  1125.         <h4 style='text-align:center;padding-bottom:0;margin-bottom:0;'>
  1126.         POLLO MOVEIS - RELATÓRIO DE CRÉDITOS E DÉBITOS</h4><hr/>";
  1127.         
  1128.         $body .= '<p style="text-align:center">
  1129.                     <strong>CLIENTE: </strong> '.$cliente->getNome().'<br/>
  1130.                     <span style="color:green;margin-top:10px;display:inline-block;"><strong>PERÍODO:</strong> '.$dataFiltroInicial->format('d/m/Y').' - ' $dataFiltroFinal->format('d/m/Y').
  1131.                 '<span></p>';
  1132.                     
  1133.         $rowsCredito = [];
  1134.         $rowsDebito  = [];
  1135.         $totalCreditos 0;
  1136.         $contDebitosLido 0;
  1137.         $contCreditosLido 0;
  1138.         $totalLancamentosIndividuais 0;
  1139.         
  1140.         //->lancamentosPorPeriodo($cliente, $dataInicial, $dataFinal);
  1141.         
  1142.         $totalDebitos  0;
  1143.         $lancamentosCredito $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)
  1144.         ->lancamentosPorPeriodo($cliente$mes'credito');
  1145.         
  1146.         $contCreditos count($lancamentosCredito);
  1147.         
  1148.         $lancamentosDebito $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)
  1149.         ->lancamentosPorPeriodo($cliente$mes'debito');
  1150.         
  1151.         $contDebitos count($lancamentosDebito);
  1152.         
  1153.         $lancamentos $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)
  1154.         ->lancamentosPorPeriodo($cliente$mes);
  1155.         
  1156.         foreach($lancamentos as $lancamento) {
  1157.             
  1158.             $numeroPedido '<a href="https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $lancamento->getNota().'&nf=n">'.$lancamento->getNota().'</a>';
  1159.             
  1160.             $pedidoEntity $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$lancamento->getNota()]);
  1161.             if($pedidoEntity instanceof EntregaPedido){
  1162.                 if($pedidoEntity->getNotas()!=null && $pedidoEntity->getNotas()!=''){
  1163.                     $numeroPedido '<a target="_blank" href="https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p='.$lancamento->getNota().'&nf=n">'.$lancamento->getNota().'</a>' ' - <a target="_blank" href="https://polo.srvtmp.com.br/img_notas/'.$pedidoEntity->getNotas().'">Foto NF</a>';
  1164.                 }
  1165.             }
  1166.             
  1167.             if($lancamento->getTipo()=='credito'){
  1168.                 $contCreditosLido++;
  1169.                 $rowsCredito[] = '<tr>
  1170.                                     <td style="text-align:center;font-size:11px;">'.$lancamento->getData()->format('d/m/Y').'</td>
  1171.                                     <td style="text-align:center;font-size:11px;">'.$numeroPedido.'</td>
  1172.                                     <td style="color:green;text-align:right;font-size:11px;" colspan="2">R$ '.number_format($lancamento->getValor(), 2',''.').'</td>
  1173.                                     <td style="text-align:left;font-size:11px;" width="25%">'.$lancamento->getObs().'</td>
  1174.                                   <tr>';
  1175.                                   
  1176.                 $totalCreditos +=$lancamento->getValor();
  1177.                 if($contCreditosLido==$contCreditos){
  1178.                     $rowsCredito[] = '<tr>
  1179.                                         <td colspan="4" style="text-align:right;font-size:11px;"><strong>Total</strong></td>
  1180.                                         <td style="color:green;text-align:left;font-size:11px;">R$ '.number_format($totalCreditos2',''.').'</td>
  1181.                                       <tr>';
  1182.                 }
  1183.                 
  1184.                                   
  1185.             } else {
  1186.                 
  1187.                 $lancamentos $this->getLancamentosPorPedido($lancamento->getId());
  1188.                 $totalLancamentosIndividuais += $lancamentos['total'];
  1189.                 
  1190.                 $tdLancamentos '';
  1191.                 foreach ($lancamentos['lancamentos'] as $lancamentoIndividual){
  1192.                     $tdLancamentos .= '<tr>
  1193.                                             <td style="color:blue;font-size:11px;">'.$lancamentoIndividual['valor'].'</td>
  1194.                                             <td style="color:blue;font-size:11px;">'.$lancamentoIndividual['data'].'</td>
  1195.                                             <td style="color:blue;font-size:11px;">'.$lancamentoIndividual['tipo'].'</td>
  1196.                                         </tr>';
  1197.                 }
  1198.                 
  1199.                 $tableLancamentos = (count($lancamentos['lancamentos'])>0) ? '<table width="100%" border="0">'.$tdLancamentos.'</table>' '';
  1200.                 
  1201.                 $contDebitosLido++;
  1202.                 
  1203.                 $backGroundPago ''
  1204.                 $isPago ''
  1205.                 
  1206.                 if($lancamento->getIsPago()){
  1207.                     $backGroundPago 'style="background-color:#7FFFD4 !important;"';
  1208.                     $isPago=" - PG";
  1209.                 }
  1210.                     
  1211.                 $rowsDebito[] = '<tr '.$backGroundPago.'>
  1212.                                     <td style="text-align:center;font-size:11px;">'.$lancamento->getData()->format('d/m/Y').$isPago.'</td>
  1213.                                     <td style="text-align:center;font-size:11px;">'.$numeroPedido.'</td>
  1214.                                     <td style="color:red;text-align:right;font-size:11px;">R$ '.number_format($lancamento->getValor(), 2',''.').'</td>
  1215.                                     <td>'.$tableLancamentos.'</td>
  1216.                                     <td style="text-align:left;font-size:11px;" width="25%">'.$lancamento->getObs().'</td>
  1217.                                   <tr>';
  1218.                                   
  1219.                 if($lancamento->getIsCalcula()){
  1220.                     $totalDebitos +=$lancamento->getValor();
  1221.                 }                 
  1222.                 
  1223.                 if($contDebitosLido==$contDebitos){
  1224.                     $rowsDebito[] = '<tr>
  1225.                                         <td colspan="4" style="text-align:right;font-size:11px;"><strong>Total de débitos de pedidos</strong></td>
  1226.                                         <td style="color:red;text-align:left;font-size:11px;">R$ '.number_format($totalDebitos2',''.').'</td>
  1227.                                       <tr>';
  1228.                     $rowsDebito[] = '<tr>
  1229.                                         <td colspan="4" style="text-align:right;font-size:11px;"><strong>Valores pagos ligados aos pedidos</strong></td>
  1230.                                         <td style="color:blue;text-align:left;font-size:11px;">R$ '.number_format($totalLancamentosIndividuais2',''.').'</td>
  1231.                                       <tr>';
  1232.                 }
  1233.             }
  1234.         }
  1235.         
  1236.         
  1237.         $body .= '<table style="margin-top:20px;" width="100%" cellspacing="1" cellpadding="2" border="1">
  1238.                   
  1239.                         <tr>
  1240.                             <td colspan="5" style="text-align:center;color:red;"><strong>Débitos</strong></td>
  1241.                         <tr>
  1242.                         
  1243.                         <tr style="background-color:#ddd;">
  1244.                             <td style="text-align:center;font-size:11px;"><strong>Data</strong></td>
  1245.                             <td style="text-align:center;font-size:11px;"><strong>Pedido</strong></td>
  1246.                             <td style="text-align:center;font-size:11px;"><strong>À pagar</strong></td>
  1247.                             <td style="text-align:center;font-size:11px;"><strong>Pagamentos efetuados neste pedido</strong></td>
  1248.                             <td style="text-align:center;font-size:11px;"><strong>Observação</strong></td>
  1249.                         <tr>
  1250.                         
  1251.                         '.implode('',$rowsDebito).'
  1252.         
  1253.                      </table>';
  1254.                      
  1255.         $body .= '<table style="margin-top:30px;" width="100%" cellspacing="1" cellpadding="2" border="1">
  1256.                         
  1257.                         <tr style="background-color:#ddd;">
  1258.                             <td colspan="5" style="text-align:center;color:green;"><strong>Créditos fora dos pedidos</strong></td>
  1259.                         <tr>
  1260.                         
  1261.                         <tr>
  1262.                             <td style="text-align:center;font-size:11px;"><strong>Data</strong></td>
  1263.                             <td style="text-align:center;font-size:11px;"><strong>Pedido</strong></td>
  1264.                             <td style="text-align:right;font-size:11px;" colspan="2"><strong>Valor</strong></td>
  1265.                             <td style="text-align:center;font-size:11px;"><strong>Observação</strong></td>
  1266.                         <tr>
  1267.                         
  1268.                         '.implode('',$rowsCredito).'
  1269.         
  1270.                      </table>';
  1271.                      
  1272.                      
  1273.         $totalCreditos += $totalLancamentosIndividuais;
  1274.         $saldo $totalCreditos $totalDebitos;
  1275.         $color = ($saldo>=0) ? 'green' 'red';
  1276.         
  1277.         $body .= '<p style="text-align:right;font-size:11px;"><strong>Saldo Total: </strong> <span style="color:'.$color.';">R$ '.number_format($saldo2',''.').'</span><p>';
  1278.         
  1279.         
  1280.         $htmlBase '<!DOCTYPE html>
  1281.                 <html>
  1282.                 <head>
  1283.                     <meta charset="utf-8">
  1284.                     <meta name="viewport" content="width=device-width, initial-scale=1">
  1285.                     <title>Pollo Distribuidora - Relatório Créditos e Débitos Revendedor</title>
  1286.                 
  1287.                     <style type="text/css">
  1288.                     </style>
  1289.                     <body>
  1290.                     
  1291.                         '.$body.'
  1292.                     
  1293.                     </body>
  1294.                 </html>';
  1295.                         
  1296.         if (get_magic_quotes_gpc()) {
  1297.             $htmlBase stripslashes($htmlBase);
  1298.         }
  1299.         
  1300.         $options = new Options();
  1301.         $options->set('defaultFont''Helvetica');
  1302.         $options->set('isHtml5ParserEnabled'true);
  1303.         $dompdf = new Dompdf($options);
  1304.         $dompdf->loadHtml($htmlBase);
  1305.         $dompdf->setPaper('A4');
  1306.         
  1307.         // Renderize o PDF (processa HTML em PDF)
  1308.         $dompdf->render();
  1309.                 
  1310.         // Obtém o conteúdo do PDF gerado
  1311.         $output $dompdf->output();
  1312.         
  1313.         if($zap=='s') {
  1314.             
  1315.             $nomeArquivoAmigavel 'Relatório de Créditos e Débitos - Pollo Distribuidora';
  1316.             $fileName 'relatorio-credito-debito-pollo-distribuidora-'.$cliente->getCnpj();
  1317.             $pathSave '/www/wwwroot/gestor.moveispollo.com.br/public/' $fileName '.pdf';
  1318.             file_put_contents($pathSave$output);
  1319.             
  1320.             $urlPdf 'https://polo.srvtmp.com.br/' $fileName '.pdf';
  1321.             
  1322.             $numeroTelefones explode('|'$cliente->getTelefone());
  1323.             
  1324.             if(count($numeroTelefones)>=1) {
  1325.                 $numeroTelefone $this->filterCelular($numeroTelefones[0]);
  1326.                 $numeroTelefone '55' $numeroTelefone;
  1327.                 $this->sendMensagemViaWhatsapp('pdf'$numeroTelefone$nomeArquivoAmigavel null$nomeArquivoAmigavel$urlPdfnull);
  1328.             }
  1329.             
  1330.             // foreach ($numeroTelefones as $numeroTelefone) {
  1331.                 
  1332.             //     $numeroTelefone = $this->filterCelular($numeroTelefone);
  1333.             //     $numeroTelefone = '55' . $numeroTelefone;
  1334.             //     $this->sendMensagemViaWhatsapp('pdf', $numeroTelefone, $nomeArquivoAmigavel , null, $nomeArquivoAmigavel, $urlPdf, null);
  1335.             // }
  1336.             // Apagar arquivo PDF
  1337.             
  1338.             return new JsonResponse([], 200);
  1339.             
  1340.         }
  1341.         
  1342.         // Configuração da resposta HTTP para exibir o PDF no navegador
  1343.         header('Content-Type: application/pdf');
  1344.         header('Content-Disposition: inline; filename="relatorio-credito-debito-pollo-distribuidora.pdf"');
  1345.         header('Cache-Control: private, max-age=0, must-revalidate');
  1346.         header('Pragma: public');
  1347.         header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
  1348.         header('Last-Modified: ' gmdate('D, d M Y H:i:s') . ' GMT');
  1349.         
  1350.         // Envia o conteúdo do PDF para o navegador
  1351.         echo $output;
  1352.         
  1353.         exit;
  1354.     }
  1355.     
  1356.     private function filterCelular($telefone) {
  1357.         $telefonetrim(str_replace('/'''str_replace(' '''str_replace('-'''str_replace(')'''str_replace('('''$telefone))))));
  1358.         return $telefone;
  1359.     }
  1360.     
  1361.     function formatarTelefone($telefone) {
  1362.         // Remove todos os caracteres não numéricos
  1363.         $telefone preg_replace('/[^0-9]/'''$telefone);
  1364.     
  1365.         // Aplica a formatação desejada
  1366.         if (strlen($telefone) >= 10) {
  1367.             // Formato para números com código de país e estado
  1368.             $codigoPais substr($telefone0strlen($telefone) - 10);
  1369.             $codigoEstado substr($telefone, -102);
  1370.             $numeroLocal substr($telefone, -8);
  1371.     
  1372.             // Verifica se o número de telefone tem um dígito a mais no celular
  1373.             if (strlen($numeroLocal) == 9) {
  1374.                 $numeroLocal '9' $numeroLocal// Adiciona o 9 no início
  1375.             }
  1376.     
  1377.             return '+' $codigoPais ' (' $codigoEstado ') ' substr_replace($numeroLocal'-'40);
  1378.         } else {
  1379.             // Retorna o número original se não for possível formatar
  1380.             return $telefone;
  1381.         }
  1382.     }
  1383.     /**
  1384.      * @Route("/app-externo/drive/clientes/deactivate", name="clientes_drive_deactivate", methods={"POST"})
  1385.      */
  1386.     public function desativarClientesDriveAction(Request $request)
  1387.     {
  1388.         $data json_decode($request->getContent(), false);
  1389.         $cliente $this->getDoctrine()->getRepository(ClienteDrive::class)->find($data->id);
  1390.         if(!$cliente instanceof ClienteDrive){
  1391.             return new JsonResponse([], 400);
  1392.         }
  1393.         
  1394.         $cliente->setIsActive(false);
  1395.         $this->getDoctrine()->getManager()->flush();
  1396.         
  1397.         return new JsonResponse([], 200);
  1398.         
  1399.     }
  1400.     
  1401.     /**
  1402.      * @Route("/app-externo/drive/clientes", name="clientes_drive", methods={"GET"})
  1403.      */
  1404.     public function clientesDriveAction(Request $request)
  1405.     {
  1406.         $clientes $this->getDoctrine()->getRepository(ClienteDrive::class)->findBy(['isActive'=>true],['nome'=>'asc']);
  1407.         $clientesData = [];
  1408.         foreach ($clientes as $cliente) {
  1409.             
  1410.             $numeroTelefones explode('|',$cliente->getTelefone());
  1411.             $numeroTelefonesData = [];
  1412.             
  1413.             foreach ($numeroTelefones as $numeroTelefone) {
  1414.                 
  1415.                 $numeroTelefone $this->filterCelular($numeroTelefone);
  1416.                 if(!empty($numeroTelefone)){
  1417.                     $numeroTelefone '55' $numeroTelefone;
  1418.                     $numeroTelefonesData[] = $numeroTelefone//$this->formatarTelefone($numeroTelefone); 
  1419.                 } else {
  1420.                     $numeroTelefonesData[] = 'Não informado';
  1421.                 }
  1422.             }
  1423.         
  1424.             $clientesData[] = [
  1425.                 'id' => $cliente->getId(),
  1426.                 'nome' => $cliente->getNome(),
  1427.                 'cnpj' => $cliente->getCnpj(),
  1428.                 'telefones' => implode(' - '$numeroTelefonesData),
  1429.                 'obs' => $cliente->getObs()
  1430.             ];
  1431.         }
  1432.         
  1433.         return new JsonResponse($clientesData200);
  1434.     }
  1435.     
  1436.     /**
  1437.      * @Route("/app-externo/drive/updateobs", name="drive_update_obs", methods={"POST"})
  1438.      */
  1439.     public function updateObsDriveAction(Request $request)
  1440.     {
  1441.         $data json_decode($request->getContent(), false);
  1442.         
  1443.         if($data->tipo=='lancamento'){
  1444.             $lancamento $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
  1445.             if(!$lancamento instanceof LancamentoClienteDrive) {
  1446.                 return new JsonResponse([], 400);
  1447.             }
  1448.         } else {
  1449.             $lancamento $this->getDoctrine()->getRepository(ClienteDrive::class)->find($data->id);
  1450.             if(!$lancamento instanceof ClienteDrive) {
  1451.                 return new JsonResponse([], 400);
  1452.             }
  1453.         }
  1454.         
  1455.         $lancamento->setObs($data->obs);
  1456.         $this->getDoctrine()->getManager()->flush();
  1457.         
  1458.         return new JsonResponse([], 200);
  1459.     }
  1460.     
  1461.     /**
  1462.      * @Route("/app-externo/drive/updatevalor", name="drive_update_valor", methods={"POST"})
  1463.      */
  1464.     public function updateValorDriveAction(Request $request)
  1465.     {
  1466.         $data json_decode($request->getContent(), false);
  1467.         $lancamento $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
  1468.         if(!$lancamento instanceof LancamentoClienteDrive) {
  1469.             return new JsonResponse([], 400);
  1470.         }
  1471.         
  1472.         $valor preg_replace("/[^0-9,.]/"""$data->valor);
  1473.         $valor str_replace("."""$valor);
  1474.         $valor str_ireplace(',','.'$valor);
  1475.         
  1476.         $lancamento->setValor($valor);
  1477.         $this->getDoctrine()->getManager()->flush();
  1478.         
  1479.         return new JsonResponse([], 200);
  1480.     }
  1481.     
  1482.     /**
  1483.      * @Route("/app-externo/drive/lancamento/externo", name="lancamento_drive_externo", methods={"POST"})
  1484.      */
  1485.     public function lancamentoClienteDriveExternoAction(Request $requestHttpClientInterface $client)
  1486.     {
  1487.         header("Access-Control-Allow-Origin: *");
  1488.         header('Access-Control-Allow-Methods: GET, POST');
  1489.         header('Access-Control-Allow-Headers: Content-Type, Authorization');
  1490.         header('Access-Control-Allow-Credentials: true');
  1491.         header('Content-Type: application/json');
  1492.         
  1493.         // Extrair as informações da requisição
  1494.         $dados explode('-'trim($request->get('requisicao')));
  1495.         $valor trim($dados[0]);
  1496.         $tipoPagamento trim($dados[1]);
  1497.         $obs null;
  1498.         
  1499.         if(count($dados)>2){
  1500.             $obs trim($dados[2]);
  1501.         }
  1502.         
  1503.         $pedidoNumber trim($request->get('pedido'));
  1504.         $dataPedido trim($request->get('data'));
  1505.         $date = \DateTime::createFromFormat('d/m/Y'$dataPedido);
  1506.         
  1507.         $valor preg_replace("/[^0-9,.]/"""$valor);
  1508.         $valor str_replace("."""$valor);
  1509.         $valor str_ireplace(',','.'$valor);
  1510.         $pedido $this->getDoctrine()
  1511.         ->getRepository(LancamentoClienteDrive::class)
  1512.         ->findOneBy(['nota' => $request->get('pedido')]);
  1513.             
  1514.         if(!$pedido instanceof LancamentoClienteDrive){
  1515.             return new JsonResponse(['message'=>'Pedido não encontrado'], 400);
  1516.         }
  1517.         
  1518.         $pagamento $this->getDoctrine()
  1519.         ->getRepository(PagamentoPedidoCreditoDebito::class)
  1520.         ->findOneBy(['tipo' => $tipoPagamento'pedido'=>$pedido'valor'=>$valor'obs'=>$obs]);
  1521.         
  1522.         if($pagamento instanceof PagamentoPedidoCreditoDebito){
  1523.             return new JsonResponse(['message'=>'Este pagamento já foi lançado'], 400);
  1524.         }
  1525.         
  1526.         $pagamento = new PagamentoPedidoCreditoDebito();
  1527.         $pagamento->setTipo($tipoPagamento);
  1528.         $pagamento->setPedido($pedido);
  1529.         $pagamento->setValor($valor);
  1530.         $pagamento->setPagoAt($date);
  1531.         $pagamento->setNota($pedidoNumber);
  1532.         $pagamento->setObs($obs);
  1533.         $pagamento->setCreatedAt(new \DateTime());
  1534.         
  1535.         $this->getDoctrine()->getManager()->persist($pagamento);
  1536.         $this->getDoctrine()->getManager()->flush();
  1537.         return new JsonResponse([], 200);
  1538.     }
  1539.     
  1540.     /**
  1541.      * @Route("/app-externo/drive/lancamento/{id}", name="lancamento_drive", methods={"POST"})
  1542.      */
  1543.     public function lancamentoClienteDriveAction(Request $request$id)
  1544.     {
  1545.         $data json_decode($request->getContent(), false);
  1546.         
  1547.         $cliente $this->getDoctrine()->getRepository(ClienteDrive::class)->find($id);
  1548.         
  1549.         if(!$cliente instanceof ClienteDrive){
  1550.             return new JsonResponse([], 400);
  1551.         }
  1552.         
  1553.         $date = \DateTime::createFromFormat('Y-m-d'$data->data);
  1554.         
  1555.         $lancamento = new LancamentoClienteDrive();
  1556.         $lancamento->setTipo('credito');
  1557.         
  1558.         $valor preg_replace("/[^0-9,.]/"""$data->valor);
  1559.         $valor str_replace("."""$valor);
  1560.         $valor str_ireplace(',','.'$valor);
  1561.         
  1562.         $lancamento->setCliente($cliente);
  1563.         $lancamento->setData($date);
  1564.         $lancamento->setNota($data->nota);
  1565.         $lancamento->setValor($valor);
  1566.         $lancamento->setTipo($data->tipo);
  1567.         $lancamento->setObs($data->obs);
  1568.         $lancamento->setCreatedAt(new \DateTime('now'));
  1569.         $lancamento->setIsCalcula(true);
  1570.         
  1571.         $this->getDoctrine()->getManager()->persist($lancamento);
  1572.         $this->getDoctrine()->getManager()->flush();
  1573.         
  1574.         return new JsonResponse([], 200);
  1575.     }
  1576.     
  1577.     /**
  1578.      * @Route("/app-externo/drive/lancamentos/cliente/{id}/{mes}", name="lancamento_clientes_drive", methods={"GET"})
  1579.      */
  1580.     public function lancamentosClienteDriveAction(Request $request$id$mes)
  1581.     {
  1582.         
  1583.         $cliente $this->getDoctrine()->getRepository(ClienteDrive::class)->find($id);
  1584.         if(!$cliente instanceof ClienteDrive) {
  1585.             return new JsonResponse([], 400);
  1586.         }
  1587.         
  1588.         $lancamentos $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->lancamentosPorPeriodo($cliente$mes);
  1589.         
  1590.         $lancamentosData = [];
  1591.         $creditos = [];
  1592.         $debitos  = [];
  1593.         $totalCreditos 0;
  1594.         $totalDebitos  0;
  1595.         $totalDebitosPagos  0;
  1596.         $saldo         0;
  1597.         $saldoPositivo true;
  1598.         $totalLancamentosIndividuais 0;
  1599.         foreach ($lancamentos as $lancamento) {
  1600.             
  1601.             if($lancamento->getTipo()=='credito'){
  1602.                 $creditos[] = [
  1603.                     'id'    => $lancamento->getId(),
  1604.                     'data'  => $lancamento->getData()->format('d/m/Y'),
  1605.                     'nota'  => $lancamento->getNota(),
  1606.                     'valor' => number_format($lancamento->getValor(), 2',''.'),
  1607.                     'obs'   => $lancamento->getObs(),
  1608.                     'isPago' => $lancamento->getIsPago(),
  1609.                     'isCalcula' => $lancamento->getIsCalcula(),
  1610.                 ];
  1611.                 $totalCreditos +=$lancamento->getValor();
  1612.                 
  1613.             } else {
  1614.                 
  1615.                 $lancamentos $this->getLancamentosPorPedido($lancamento);
  1616.                 $totalLancamentosIndividuais += $lancamentos['total'];
  1617.                         
  1618.                 $debitos[] = [
  1619.                     'id'    => $lancamento->getId(),
  1620.                     'data'  => $lancamento->getData()->format('d/m/Y'),
  1621.                     'nota'  => $lancamento->getNota(),
  1622.                     'valor' => number_format($lancamento->getValor(), 2',''.'),
  1623.                     'obs'   => $lancamento->getObs(),
  1624.                     'isPago' => $lancamento->getIsPago(),
  1625.                     'isCalcula' => $lancamento->getIsCalcula(),
  1626.                     'lancamentos' => $lancamentos['lancamentos']
  1627.                 ];
  1628.                 //$totalDebitos +=$lancamento->getValor();
  1629.                 if($lancamento->getIsCalcula()) {
  1630.                     $totalDebitos +=$lancamento->getValor();
  1631.                 }
  1632.             }
  1633.         }
  1634.         
  1635.         $totalCreditos += $totalLancamentosIndividuais;
  1636.         $saldo $totalCreditos $totalDebitos;
  1637.         $saldoPositivo = ($saldo>=0);
  1638.         
  1639.         return new JsonResponse([
  1640.             'creditos'=>$creditos
  1641.             'debitos'=>$debitos
  1642.             'totalCreditos'=>number_format($totalCreditos2',''.'), 
  1643.             'totalDebitos'=>number_format($totalDebitos2',''.'),
  1644.             'saldo'=>number_format($saldo2',''.'),
  1645.             'saldoPositivo'=>$saldoPositivo,
  1646.             'totalLancamentosIndividuais' => number_format($totalLancamentosIndividuais2',''.')
  1647.             ], 200);
  1648.     }
  1649.     
  1650.     private function getLancamentosPorPedido($pedidoRequest) {
  1651.     
  1652.         $pagamentosData = [];
  1653.         $total 0;
  1654.         
  1655.         $pagamentos $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->findBy(['pedido'=>$pedidoRequest]);
  1656.     
  1657.         foreach ($pagamentos as $pagamento) {
  1658.             $total +=$pagamento->getValor();
  1659.             $pagamentosData[] = [
  1660.                 'id'        => $pagamento->getId(),
  1661.                 'valor'     => number_format($pagamento->getValor(), 2',''.'),
  1662.                 'obs'       => $pagamento->getObs(),
  1663.                 'tipo'      => $pagamento->getTipo(),
  1664.                 'data'      => $pagamento->getPagoAt()->format('d/m/Y'),
  1665.             ];
  1666.             
  1667.         }
  1668.         
  1669.         return ['lancamentos'=>$pagamentosData'total'=>$total];
  1670.     }
  1671.     
  1672.     /**
  1673.      * @Route("/app-externo/drive/lancamentos/delete", name="lancamento_delete_drive", methods={"POST"})
  1674.      */
  1675.     public function deleteLancamentoDriveAction(Request $request)
  1676.     {
  1677.         $data json_decode($request->getContent(), false);
  1678.         $lancamento $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
  1679.         if(!$lancamento instanceof LancamentoClienteDrive) {
  1680.             return new JsonResponse([], 400);
  1681.         }
  1682.         
  1683.         // Deleta os lancamentos individuais
  1684.         $totalLancamentosIndividuais $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->findBy(['pedido'=>$lancamento]);
  1685.         foreach ($totalLancamentosIndividuais as $totalLancamentoIndividual) {
  1686.             $this->getDoctrine()->getManager()->remove($totalLancamentoIndividual);
  1687.             $this->getDoctrine()->getManager()->flush();
  1688.         }
  1689.         
  1690.         $this->getDoctrine()->getManager()->remove($lancamento);
  1691.         $this->getDoctrine()->getManager()->flush();
  1692.         
  1693.         return new JsonResponse([], 200);
  1694.         
  1695.     }
  1696.     
  1697. ###### DRIVE
  1698.     
  1699.     
  1700.     /**
  1701.      * @Route("/app-externo/teste_zap", name="teste-zap", methods={"GET"})
  1702.      */
  1703.     public function testeZapAction(KernelInterface $kernelBlingService $blingService)
  1704.     {
  1705.         
  1706.         // $acoes = [];
  1707.         
  1708.         // $acoes[] = 'Atualização de produto';
  1709.         // $acoes[] = 'Atualização de produto';
  1710.         // $acoes[] = 'Atualização de produto';
  1711.         // $acoes[] = 'Atualização de produto';
  1712.         // $acoes[] = 'Atualização de produto';
  1713.         
  1714.         // if(!$blingService->temRequisicaoDisponivel(count($acoes))){
  1715.         //     exit('Ações não permitidas');
  1716.         // }
  1717.         
  1718.         // $blingService->registraRequisicaoBling($acoes);
  1719.         // exit('Ações cadastradas');
  1720.         $numeroPedido 1234;
  1721.         $messageBody "Teste de envio de zap\nCom quebra de linha";
  1722.         
  1723.         $this->sendMensagemViaWhatsapp("img""5562983281823"$messageBody'https://polo.srvtmp.com.br/bg_promocoes/individuais/individual_1.jpeg?v=1704901159'nullnull); // Benjamim
  1724.         exit;
  1725.         
  1726.         $url    'https://isp.owenbrasil.com.br/api/global.php';
  1727.         $toquen 'Q68XUMRFAANCIQ0UK3HL6KJ5OGATTXBBUDZTG52U';
  1728.         $numeroTelefone '5562983281823';
  1729.         
  1730.         $messageBody "Teste";
  1731.         $messageBody $messageBody " - #Pollo Móveis#";
  1732.         
  1733.         $posts = array(
  1734.           'tipo'    => 'img',
  1735.           'token'   => $toquen,
  1736.           'numero'  => $numeroTelefone,
  1737.           'mensagem'=> $messageBody,
  1738.           'urlimg'  => "https://polo.srvtmp.com.br/bg_promocoes/individuais/individual_1.jpeg?v=1704901159"
  1739.         ); 
  1740.         
  1741.         $posts = array(
  1742.           'tipo'    => 'normal',
  1743.           'token'   => $toquen,
  1744.           'numero'  => $numeroTelefone,
  1745.           'mensagem'=> $messageBody
  1746.         );
  1747.     
  1748.         // // Construa a URL com os parâmetros de consulta
  1749.         // $url .= '?' . http_build_query($posts);
  1750.         
  1751.         // $curl_handle = curl_init();
  1752.         // curl_setopt($curl_handle, CURLOPT_URL, $url);
  1753.         // curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
  1754.         // curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
  1755.         // curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);
  1756.         // curl_setopt($curl_handle, CURLOPT_HTTPGET, true);
  1757.         
  1758.         // $response     = curl_exec($curl_handle);
  1759.         // $responseJson = json_decode($response);
  1760.         
  1761.         // print_r($responseJson); exit;
  1762.         
  1763.         // if($responseJson->statusCode==200){
  1764.             
  1765.         //     exit('Mensagem ID: ' . $responseJson->idMessage);
  1766.             
  1767.         // } else {
  1768.         //     exit("Mensagem não enviada!");
  1769.         // }
  1770.         
  1771.     }
  1772.     
  1773.     
  1774.     // /**
  1775.     //  * @Route("/app-externo/calcula_tolerancia_entrega", name="calcula_tolerancia_entrega", methods={"GET"})
  1776.     //  */
  1777.     // public function testeAction(KernelInterface $kernel)
  1778.     // {
  1779.     //     $dataUltimaMovimentacao = '2023-11-30 18:00:00';
  1780.     //     $dataVerificacaoScript  = '2023-12-01 12:00:00';
  1781.         
  1782.     //     echo $this->calcularDiferencaHoras($dataUltimaMovimentacao, $dataVerificacaoScript);
  1783.         
  1784.     //     // Exemplo de uso
  1785.     //     // $dataAceitacao = '2023-11-30 16:00:00';
  1786.     //     // $tolerancia = 4;
  1787.         
  1788.     //     // if ($this->ultrapassouTolerancia($dataAceitacao, $tolerancia)) {
  1789.     //     //     echo "Tolerância: $tolerancia<br/>Data aceitação: $dataAceitacao<br/><br/>Pedido ultrapassou a tolerância.\n";
  1790.     //     // } else {
  1791.     //     //     echo "Tolerância: $tolerancia<br/>Data aceitação: $dataAceitacao<br/><br/>Pedido dentro da tolerância.\n";
  1792.     //     // }
  1793.         
  1794.     //     exit;
  1795.     
  1796.     // }
  1797.             
  1798.     // function calcularDiferencaHoras($dataInicial, $dataFinal) {
  1799.     //     $dataInicio = new \DateTime($dataInicial);
  1800.     //     $dataFim = new \DateTime($dataFinal);
  1801.         
  1802.     //     // Define o horário de início e fim do expediente
  1803.     //     $horarioInicio = 8;
  1804.     //     $horarioFim = 18;
  1805.     
  1806.     //     // Inicializa a diferença total em horas
  1807.     //     $diferencaTotal = 0;
  1808.     
  1809.     //     while ($dataInicio < $dataFim) {
  1810.     //         // Calcula o horário de início e fim para o dia atual
  1811.     //         $inicioDiaAtual = clone $dataInicio;
  1812.     //         $inicioDiaAtual->setTime($horarioInicio, 0, 0);
  1813.     
  1814.     //         $fimDiaAtual = clone $dataInicio;
  1815.     //         $fimDiaAtual->setTime($horarioFim, 0, 0);
  1816.     
  1817.     //         // Calcula a diferença entre o início e o fim do dia, desconsiderando sábados e domingos
  1818.     //         if ($dataInicio->format('N') <= 5) {
  1819.     //             $diferencaDia = min($fimDiaAtual, $dataFim)->getTimestamp() - max($inicioDiaAtual, $dataInicio)->getTimestamp();
  1820.     //             $diferencaDia = max(0, $diferencaDia);
  1821.     //             $diferencaTotal += $diferencaDia;
  1822.     //         }
  1823.     
  1824.     //         // Adiciona um dia completo
  1825.     //         $dataInicio->add(new \DateInterval('P1D'));
  1826.     //     }
  1827.     
  1828.     //     // Converte a diferença total para horas
  1829.     //     $diferencaTotalHoras = $diferencaTotal / 3600;
  1830.     
  1831.     //     return $diferencaTotalHoras;
  1832.     // }
  1833.     
  1834.     // function ultrapassouTolerancia($dataAceitacao, $tolerancia) {
  1835.         
  1836.     //     $dataEntrega = new \DateTime($dataAceitacao);
  1837.     
  1838.     //     // Define o horário de início e fim do expediente
  1839.     //     $horarioInicio = 8;
  1840.     //     $horarioFim = 18;
  1841.     
  1842.     //     // Adiciona a tolerância ao horário de aceitação
  1843.     //     $dataEntrega->modify("+$tolerancia hours");
  1844.     
  1845.     //     // Ajusta o horário de início e fim para dias úteis
  1846.     //     $dataEntrega->setTime($horarioInicio, 0, 0);
  1847.     //     $dataFimExpediente = clone $dataEntrega;
  1848.     //     $dataFimExpediente->setTime($horarioFim, 0, 0);
  1849.     
  1850.     //     // Verifica se a entrega ultrapassa o expediente
  1851.     //     if ($dataEntrega > $dataFimExpediente) {
  1852.     //         // Se ultrapassar, ajusta para o próximo dia útil
  1853.     //         $dataEntrega->modify("+$horarioInicio hours");
  1854.     //     }
  1855.         
  1856.     //     var_dump($dataFimExpediente);
  1857.     
  1858.     //     $agora = new \DateTime();
  1859.     //     return $dataEntrega <= $agora;
  1860.         
  1861.     // }
  1862.     
  1863.     /**
  1864.      * @Route("/app-externo/pedidos-nao-cadastrados", name="pedidos_nao_cadastrados", methods={"POST"})
  1865.      */
  1866.     public function pedidosNaoCadastrados(Request $request)
  1867.     {
  1868.         header("Access-Control-Allow-Origin: *");
  1869.         header('Access-Control-Allow-Methods: GET, POST');
  1870.         header('Access-Control-Allow-Headers: Content-Type, Authorization');
  1871.         header('Access-Control-Allow-Credentials: true');
  1872.         header('Content-Type: application/json');
  1873.         
  1874.         //$data = json_decode($request->getContent(), false);
  1875.         //$pedidos = $data->pedidos;
  1876.         
  1877.         $pedidos $request->get('pedidos');
  1878.         $pedidos explode(','$pedidos);
  1879.         
  1880.         $pedidosNaoCadastrados = [];
  1881.         
  1882.         $connection $this->getDoctrine()->getConnection('default');
  1883.         
  1884.         foreach ($pedidos as $pedido) {
  1885.             
  1886.             $results $connection->executeQuery("
  1887.             SELECT pedido  
  1888.             FROM entrega_pedido
  1889.             WHERE pedido=$pedido AND deleted_at is null")
  1890.             ->fetchAllAssociative();
  1891.             
  1892.             if(count($results)==0){
  1893.                $pedidosNaoCadastrados[]=$pedido;
  1894.             }
  1895.         }
  1896.         
  1897.         echo json_encode($pedidosNaoCadastrados);
  1898.        exit;
  1899.     }
  1900.     
  1901.     public function temAlgumValePendente() {
  1902.         
  1903.         if(!$this->getIsAdmin()){
  1904.             return false;
  1905.         }
  1906.         
  1907.         $solicitacaoPendnte $this->getDoctrine()->getRepository(ValeSolicitacao::class)->colaboradorTemValePendente(nulltrue);
  1908.         $solicitacaoPendnte = (count($solicitacaoPendnte)) ? true false;
  1909.         return $solicitacaoPendnte;
  1910.     }
  1911.     
  1912.     
  1913.     /**
  1914.      * @Route("/app-externo/texte-api", name="texte_api", methods={"GET"})
  1915.      */
  1916.     public function testeApi(KernelInterface $kernel)
  1917.     {
  1918.         // $type           = "img";
  1919.         // $numeroTelefone = "5562983281823";
  1920.         // $messageBody    = "Teste de texto com texto";
  1921.         // $img            = "https://polo.srvtmp.com.br/frontend/images/logo.png";
  1922.         // $nomePdf        = null;
  1923.         // $urlpdf         = null;
  1924.         
  1925.         // // Envia Imagem
  1926.         // $this->sendMensagemViaWhatsappV2($type, $numeroTelefone, $messageBody, $img, $nomePdf, $urlpdf);
  1927.         
  1928.         // $type           = "text";
  1929.         // $numeroTelefone = "5562983281823";
  1930.         // $messageBody    = "Teste de texto";
  1931.         // $img            = null;
  1932.         // $nomePdf        = null;
  1933.         // $urlpdf         = null;
  1934.         
  1935.         // // Envia texto
  1936.         // $this->sendMensagemViaWhatsappV2($type, $numeroTelefone, $messageBody, $img, $nomePdf, $urlpdf);
  1937.         
  1938.         exit();
  1939.     }
  1940.     
  1941.     /**
  1942.      * @Route("/app-externo/atualiza-valores-diarios", name="atualiza_valores_diarios", methods={"POST"})
  1943.      */
  1944.     public function atualizaValoresDiarios(KernelInterface $kernel)
  1945.     {
  1946.         
  1947.         $application = new Application($kernel);
  1948.         $application->setAutoExit(false);
  1949.         $input = new ArrayInput([
  1950.             'command' => 'app:acoes-pedidos-diario',
  1951.         ]);
  1952.         // You can use NullOutput() if you don't need the output
  1953.         $output = new BufferedOutput();
  1954.         $application->run($input$output);
  1955.         
  1956.         // return the output, don't use if you used NullOutput()
  1957.         $content $output->fetch();
  1958.         // return new Response(""), if you used NullOutput()
  1959.         return new Response($content);
  1960.     }
  1961.     /**
  1962.      * @Route("/app-externo/relatorios-acompanhamento-pedidos", name="relatorios_acompanhamentos_pedidos", methods={"POST"})
  1963.      */
  1964.     public function getRelatorioAcompanhamentosPedidos(Request $request): Response
  1965.     
  1966.         
  1967.         $data json_decode($request->getContent(), false);
  1968.         $pedidos = [];
  1969.         $pedidosCodigo = [];
  1970.         
  1971.         $tipo           $data->dados->tipo// motorista, separadores, vendedor
  1972.         $usuarioID      $data->dados->id_user;
  1973.         $status         $data->dados->status;
  1974.         
  1975.         $dataInicio     $data->dataInicio;
  1976.         $dataFim        $data->dataFim;
  1977.         
  1978.         $user $this->getDoctrine()->getRepository(User::class)->find($usuarioID);
  1979.         
  1980.         if($tipo=='motorista') {
  1981.             $pedidos $this->getTotalPedidosPorUsuarioEstatus($user,$status,'colaboradorUser'''$dataInicio$dataFimtrue);
  1982.         } else if($tipo=='separador') {
  1983.             
  1984.             // MUDAR QUERY PARA LIKE
  1985.             
  1986.             //$pedidos = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','separador', $user->getEmail(), $dataInicio, $dataFim, true);
  1987.             
  1988.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoSeparador($user->getEmail(), true$dataInicio$dataFim);
  1989.             
  1990.         } else if($tipo=='vendedor') {
  1991.             $pedidos $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','vendedor_pedidos'$user->getEmail(), $dataInicio$dataFimtrue$data->dados->periodo);
  1992.         } else if($tipo=='auxiliar') {
  1993.             $pedidos $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','auxiliares'$user->getEmail(), $dataInicio$dataFimtrue);
  1994.         }
  1995.             
  1996.         foreach ($pedidos as $pedido) {
  1997.             $pedidosCodigo[] = (empty($pedido->getPedido())) ? $pedido->getNotaFiscal() : $pedido->getPedido();
  1998.         }
  1999.         
  2000.         $oss $this->getDoctrine()->getRepository(OrdemServico::class)->getOsNaData($dataInicio$dataFim$user);
  2001.         
  2002.         foreach ($oss as $os) {
  2003.             $pedidosCodigo[] = 'OS: ' $os->getNumero();
  2004.         }
  2005.         
  2006.         echo implode('-',$pedidosCodigo);
  2007.         exit;
  2008.     }
  2009.     
  2010.     private function getTotalOsAceitaPorUsuario($user$dataInicio$dataFim) {
  2011.         
  2012.         // $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$userEmail]);
  2013.         
  2014.         // if(!$user instanceof User){
  2015.             
  2016.         //     return 0;
  2017.         // }
  2018.         
  2019.         $obss $this->getDoctrine()->getRepository(OrdemServico::class)->getOsNaData($dataInicio$dataFim$user);
  2020.         
  2021.         //echo ($userEmail . ' - TOTAL: ' . count($obss));
  2022.         
  2023.         return count($obss);
  2024.         
  2025.     }
  2026.     
  2027.     /**
  2028.      * @Route("/app-externo/relatorios-acompanhamento", name="relatorios_acompanhamentos", methods={"GET"})
  2029.      */
  2030.     public function getRelatorioAcompanhamentos(Request $request): Response
  2031.     
  2032.         
  2033.         $dados = [
  2034.             'motoristas'    => [],
  2035.             'separadores'   => [],
  2036.             'vendedores'    => [],
  2037.         ];
  2038.         
  2039.         //return new JsonResponse($dados, 200);
  2040.         
  2041.         $users $this->getDoctrine()->getRepository(User::class)->findAll();
  2042.         
  2043.         $dataInicio     $request->get('dataInicio');
  2044.         $dataFim        $request->get('dataFim');
  2045.         
  2046.         foreach ($users as $user) {
  2047.             
  2048.             if(in_array('ROLE_ENTREGADOR'$user->getRoles())) {
  2049.                 
  2050.                 if($user->getNome()=='Richardy'){continue;}
  2051.                 
  2052.                 $pedidosAceitos  $this->getTotalPedidosPorUsuarioEstatus($user,'aceito','colaboradorUser'''$dataInicio$dataFim);
  2053.                 $pedidosTransito 0//$this->getTotalPedidosPorUsuarioEstatus($user,'transito','colaboradorUser', '', $dataInicio, $dataFim);
  2054.                 $pedidosEntregue 0//$this->getTotalPedidosPorUsuarioEstatus($user,'entregue','colaboradorUser', '', $dataInicio, $dataFim);
  2055.                 $pedidosBaixado  0//$this->getTotalPedidosPorUsuarioEstatus($user,'baixado','colaboradorUser', '', $dataInicio, $dataFim);
  2056.                 
  2057.                 $totalOs $this->getTotalOsAceitaPorUsuario($user$dataInicio$dataFim);
  2058.                 $pedidosAceitos +=$totalOs;
  2059.                 
  2060.                 $total $pedidosAceitos+$pedidosTransito+$pedidosEntregue+$pedidosBaixado;
  2061.                 
  2062.                 $dados['motoristas'][] = [
  2063.                     'nome'      => $user->getNome(),
  2064.                     'id'        => $user->getId(),
  2065.                     'aceito'    => $pedidosAceitos,
  2066.                     'transito'  => $pedidosTransito,
  2067.                     'entregue'  => $pedidosEntregue,
  2068.                     'baixado'   => $pedidosBaixado,
  2069.                     'total'     => $total
  2070.                 ];
  2071.                 
  2072.             }
  2073.             
  2074.             if(in_array('ROLE_SEPARADOR'$user->getRoles())) {
  2075.                 
  2076.                 //if($user->getNome()=='Richardy'){continue;}
  2077.                 
  2078.                 $totalAceitos   $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','separador'$user->getEmail(), $dataInicio$dataFim);
  2079.                 $totalPronto    $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'pronto','separador'$user->getEmail(), $dataInicio$dataFim);
  2080.                 $totalbaixados  $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'baixado','separador'$user->getEmail(), $dataInicio$dataFim);
  2081.                 
  2082.                 $dados['separadores'][] = [
  2083.                     'nome'          => $user->getNome(),
  2084.                     'id'            => $user->getId(),
  2085.                     'aceito'        => $totalAceitos,
  2086.                     'pronto'        => $totalPronto,
  2087.                     'baixado'       => $totalbaixados
  2088.                 ];
  2089.                 
  2090.             }
  2091.             
  2092.             
  2093.             
  2094.             if(in_array('ROLE_VENDEDOR'$user->getRoles())) {
  2095.                 
  2096.                 if($user->getNome()=='Junior'){continue;}
  2097.                 
  2098.                 $totalDia $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'dia','vendedor'$user->getEmail(), $dataInicio$dataFim);
  2099.                 $totalMes $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'mes','vendedor'$user->getEmail(), $dataInicio$dataFim);
  2100.                 
  2101.                 $dados['vendedores'][] = [
  2102.                     'nome'          => $user->getNome(),
  2103.                     'id'            => $user->getId(),
  2104.                     'dia'           => number_format($totalDia2',''.'),
  2105.                     'mes'           => number_format($totalMes2',''.'),
  2106.                     'total'         => $totalMes
  2107.                 ];
  2108.                 
  2109.             }
  2110.             
  2111.             if(in_array('ROLE_AUX_ENTREGADOR'$user->getRoles())) {
  2112.                 
  2113.                 $totalDia $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'dia','auxiliares'$user->getEmail(), $dataInicio$dataFim);
  2114.                 $totalMes $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'mes','auxiliares'$user->getEmail(), $dataInicio$dataFim);
  2115.                 
  2116.                 // Pegar total de os aceita
  2117.                 $totalOs $this->getTotalOsAceitaPorUsuario($user$dataInicio$dataFim);
  2118.                 $totalMes += $totalOs;
  2119.                 
  2120.                 $dados['auxiliares'][] = [
  2121.                     'nome'          => $user->getNome(),
  2122.                     'id'            => $user->getId(),
  2123.                     'dia'           => number_format($totalDia2',''.'),
  2124.                     'mes'           => number_format($totalMes2',''.'),
  2125.                     'total'         => $totalMes
  2126.                 ];
  2127.             }
  2128.             
  2129.         }
  2130.     
  2131.         $totalAceitos   $this->getTotalPedidosPorUsuarioEstatus('João Marcos''aceito''separador''joao_marcos'$dataInicio$dataFim);
  2132.         $totalPronto    $this->getTotalPedidosPorUsuarioEstatus('João Marcos''pronto''separador''joao_marcos'$dataInicio$dataFim);
  2133.         $totalbaixados  $this->getTotalPedidosPorUsuarioEstatus('João Marcos''baixado''separador''joao_marcos'$dataInicio$dataFim);
  2134.                 
  2135.         $dados['separadores'][] = [
  2136.             'nome'      => 'João Marcos',
  2137.             'id'        => 12,
  2138.             'aceito'    => $totalAceitos,
  2139.             'pronto'    => $totalPronto,
  2140.             'baixado'   => $totalbaixados
  2141.         ];
  2142.                 
  2143.         $totalDia $this->getTotalPedidosPorUsuarioEstatus('Richardy','dia','vendedor','richardy'$dataInicio$dataFim);
  2144.         $totalMes $this->getTotalPedidosPorUsuarioEstatus('Richardy','mes','vendedor','richardy'$dataInicio$dataFim);
  2145.                 
  2146.         $dados['vendedores'][] = [
  2147.             'nome'      => 'Richardy',
  2148.             'id'        => 15,
  2149.             'dia'       => number_format($totalDia2',''.'),
  2150.             'mes'       => number_format($totalMes2',''.'),
  2151.             'total'     => $totalMes
  2152.         ];
  2153.         
  2154.         $totalAceitos   $this->getTotalPedidosPorUsuarioEstatus('Richardy''aceito''separador''richardy'$dataInicio$dataFim);
  2155.         $totalPronto    $this->getTotalPedidosPorUsuarioEstatus('Richardy''pronto''separador''richardy'$dataInicio$dataFim);
  2156.         $totalbaixados  $this->getTotalPedidosPorUsuarioEstatus('Richardy''baixado''separador''richardy'$dataInicio$dataFim);
  2157.                 
  2158.         $dados['separadores'][] = [
  2159.             'nome'      => 'Richardy',
  2160.             'id'        => 15,
  2161.             'aceito'    => $totalAceitos,
  2162.             'pronto'    => $totalPronto,
  2163.             'baixado'   => $totalbaixados
  2164.         ];
  2165.         
  2166.         $totalDiaOutros $this->getTotalPedidosPorUsuarioEstatus('outros','dia','vendedor','outros'$dataInicio$dataFim);
  2167.         $totalMesOutros $this->getTotalPedidosPorUsuarioEstatus('outros','mes','vendedor','outros'$dataInicio$dataFim);
  2168.         
  2169.         $dados['vendedores'][] = [
  2170.             'nome'      => 'Outros',
  2171.             'id'        => 16,
  2172.             'dia'       => number_format($totalDiaOutros2',''.'),
  2173.             'mes'       => number_format($totalMesOutros2',''.'),
  2174.             'total'     => $totalMesOutros
  2175.         ];
  2176.         
  2177.         usort($dados['vendedores'], function($a$b) {
  2178.             return $b['total'] - $a['total'];
  2179.         });
  2180.         
  2181.         usort($dados['separadores'], function($a$b) {
  2182.             return $b['aceito'] - $a['aceito'];
  2183.         });
  2184.         
  2185.         usort($dados['motoristas'], function($a$b) {
  2186.             return $b['total'] - $a['total'];
  2187.         });
  2188.         
  2189.         usort($dados['auxiliares'], function($a$b) {
  2190.             return $b['total'] - $a['total'];
  2191.         });
  2192.         
  2193.         $dados['maior_motorista'] = $dados['motoristas'][0]['total'];
  2194.         $dados['maior_separador'] = $dados['separadores'][0]['aceito'];
  2195.         $dados['maior_vendedor']  = $dados['vendedores'][0]['total'];
  2196.         $dados['maior_auxiliar']  = $dados['auxiliares'][0]['total'];
  2197.         
  2198.         $dados['montagens']       = $this->getMontagensRelatorio();
  2199.         
  2200.         usort($dados['montagens'], function($a$b) {
  2201.             return $b['pedido'] - $a['pedido'];
  2202.         });
  2203.         
  2204.         return new JsonResponse($dados200);
  2205.         
  2206.     }
  2207.     
  2208.     
  2209.     private function pedidoFinalizado($montagensFinalizadas$pedidoNumero) {
  2210.         
  2211.         $data '';
  2212.         
  2213.         foreach ($montagensFinalizadas as $pedido) {
  2214.             if($pedido['pedido']==$pedidoNumero){
  2215.                 $data $pedido['data'];
  2216.             }
  2217.         }
  2218.         
  2219.         return $data;
  2220.         
  2221.     }
  2222.     
  2223.     function extrairNumero($s) {
  2224.         if (preg_match('/\d+/'$s$matches)) {
  2225.             return intval($matches[0]);
  2226.         } else {
  2227.             return null;
  2228.         }
  2229.     }
  2230.     
  2231.     private function getMontagensRelatorio() {
  2232.         
  2233.         $dados = [];
  2234.         $montagensFinalizadas $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('finalizados');
  2235.         $montagensFinalizadasData = [];
  2236.         foreach ($montagensFinalizadas as $pedido) {
  2237.             
  2238.             $pedidoReplace $this->extrairNumero($pedido->getPedido());
  2239.             $montagensFinalizadasData[] = [
  2240.                 'id' => $pedido->getId(),
  2241.                 'pedido' => $pedidoReplace,
  2242.                 'montador' => 'Finalizados',
  2243.                 'cor' => 'blue',
  2244.                 'data' => ($pedido->getPedidoMontandoMontagemFinalizada() instanceof \DateTime) ? $pedido->getPedidoMontandoMontagemFinalizada()->format('d/m/Y H:i') : ''
  2245.             ];
  2246.         }
  2247.         
  2248.         
  2249.         $montagensRonald $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('Ronald');
  2250.         foreach ($montagensRonald as $pedido) {
  2251.             
  2252.             $data $this->pedidoFinalizado($montagensFinalizadasData,$pedido->getPedido());
  2253.             $cor = ($data!='') ? 'blue' 'black';
  2254.             
  2255.             $pedidoReplace $this->extrairNumero($pedido->getPedido());
  2256.             
  2257.             $dados[] = [
  2258.                 'id' => $pedido->getId(),
  2259.                 'pedido' => $pedidoReplace,
  2260.                 'montador' => 'Ronald',
  2261.                 'cor' => $cor,
  2262.                 'data' => ($pedido->getPedidoMontandoRonald() instanceof \DateTime) ? $pedido->getPedidoMontandoRonald()->format('d/m/Y H:i') : '',
  2263.                 'finalizado' => $data
  2264.             ];
  2265.         }
  2266.         
  2267.         $montagensFabio $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('Fabio');
  2268.         foreach ($montagensFabio as $pedido) {
  2269.             $data $this->pedidoFinalizado($montagensFinalizadasData,$pedido->getPedido());
  2270.             $cor = ($data!='') ? 'blue' 'black';
  2271.             $pedidoReplace str_replace('-Assistência',''$pedido->getPedido());
  2272.             $dados[] = [
  2273.                 'id' => $pedido->getId(),
  2274.                 'pedido' => $pedidoReplace,
  2275.                 'montador' => 'Fábio',
  2276.                 'cor' => $cor,
  2277.                 'data' => ($pedido->getPedidoMontandoFabio() instanceof \DateTime) ? $pedido->getPedidoMontandoFabio()->format('d/m/Y H:i') : '',
  2278.                 'finalizado' => $data
  2279.             ];
  2280.             
  2281.         }
  2282.         
  2283.         
  2284.         $montagensRian $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('Rian');
  2285.         foreach ($montagensRian as $pedido) {
  2286.             
  2287.             $data $this->pedidoFinalizado($montagensFinalizadasData,$pedido->getPedido());
  2288.             $cor = ($data!='') ? 'blue' 'black';
  2289.             
  2290.             $pedidoReplace str_replace('-Assistência',''$pedido->getPedido());
  2291.             
  2292.             $dados[] = [
  2293.                 'id' => $pedido->getId(),
  2294.                 'pedido' => $pedidoReplace,
  2295.                 'montador' => 'Rian',
  2296.                 'cor' => $cor,
  2297.                 'data' => ($pedido->getPedidoMontandoRian() instanceof \DateTime) ? $pedido->getPedidoMontandoRian()->format('d/m/Y H:i') : '',
  2298.                 'finalizado' => $data
  2299.             ];
  2300.             
  2301.         }
  2302.         
  2303.         return $dados;
  2304.         
  2305.     }
  2306.     
  2307.     private function getTotalPedidosPorUsuarioEstatus($user$status$tipoColaborador$userEmail=''$dataInicio$dataFim$devolveEntidades=false$periodo=null) {
  2308.         
  2309.         if($tipoColaborador=='colaboradorUser') {
  2310.             
  2311.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosParaRelatorioDesempenho($user$status$tipoColaborador$userEmail$dataInicio$dataFim);
  2312.             
  2313.         } else if($tipoColaborador=='separador') {
  2314.             
  2315.             //  MUDAR PARA LIKE TAMBEM
  2316.             //$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosParaRelatorioDesempenho($user, $status, $tipoColaborador, $userEmail, $dataInicio, $dataFim);
  2317.             
  2318.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoSeparador($usertrue$dataInicio$dataFim);
  2319.             
  2320.         } else if($tipoColaborador=='outros') {
  2321.             
  2322.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoOutros($user$status);
  2323.             $pedidos = [];
  2324.             
  2325.         } else if($tipoColaborador=='vendedor') {
  2326.             // $jsonFile   = ($status=='dia') ? '/www/wwwroot/gestor.moveispollo.com.br/db_local_today.json' : '/www/wwwroot/gestor.moveispollo.com.br/db_local.json';
  2327.             // $jsonData   = file_get_contents($jsonFile);
  2328.             // $data       = json_decode($jsonData, true);
  2329.             
  2330.             // return $data[$user];
  2331.             
  2332.             $usuarios = [
  2333.                 'nicholas'  => 0,
  2334.                 'guilherme' => 0,
  2335.                 'willian'   => 0,
  2336.                 'iury'      => 0,
  2337.                 'richardy'  => 0,
  2338.                 'eduardo'   => 0,
  2339.                 'outros'    => 0,
  2340.             ];
  2341.             
  2342.             $usuariosResult = [
  2343.                 'total'     => 0,
  2344.                 'nicholas'  => 0,
  2345.                 'guilherme' => 0,
  2346.                 'willian'   => 0,
  2347.                 'iury'      => 0,
  2348.                 'richardy'  => 0,
  2349.                 'eduardo'   => 0,
  2350.                 'outros'    => 0,
  2351.             ];
  2352.             
  2353.             $total 0;
  2354.             $dia = ($status=='dia') ? true :  false;
  2355.             foreach ($usuarios as $key => $value){
  2356.                 $usuarioTotal $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtual($key,$dia);
  2357.                 $usuariosResult[$key] = $usuarioTotal;
  2358.             }
  2359.             
  2360.             $usuariosResult['total'] = $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtual($userEmail,true);
  2361.             
  2362.             if(!isset($usuariosResult[$userEmail])){
  2363.                 return 0;
  2364.             }
  2365.             
  2366.             return $usuariosResult[$userEmail];
  2367.             
  2368.         } else if($tipoColaborador=='vendedor_pedidos') {
  2369.             
  2370.             switch($userEmail) {
  2371.                 case 'nicholas':
  2372.                     $user 'NICHOLLAS';
  2373.                 break;
  2374.                 
  2375.                 case 'guilherme':
  2376.                     $user 'Guilherme Leão';
  2377.                 break;
  2378.                 
  2379.                 case 'willian':
  2380.                     $user 'WILLIAN LOPES';
  2381.                 break;
  2382.                 
  2383.                 case 'iury':
  2384.                     $user 'IURY SOUSA';
  2385.                 break;
  2386.                 
  2387.                 case 'joao_marcos':
  2388.                     $user 'João Marcos';
  2389.                 break;
  2390.                 
  2391.                 case 'richardy':
  2392.                     $user 'Richardy';
  2393.                 break;
  2394.                 
  2395.                 case 'eduardo':
  2396.                     $user 'Eduardo Gabriel';
  2397.                 break;
  2398.                 
  2399.                 case 'bruno@moveispollo.com.br':
  2400.                     $user 'Bruno Oliveira';
  2401.                 break;
  2402.             }
  2403.             
  2404.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)
  2405.             ->getPedidosParaRelatorioDesempenho($user$status'vendedor'$userEmail$dataInicio$dataFim$periodo);
  2406.             
  2407.         } else if($tipoColaborador=='auxiliares') {
  2408.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)
  2409.             ->getPedidosParaRelatorioDesempenho($user$status'auxiliares'$userEmail$dataInicio$dataFim);
  2410.         }
  2411.         
  2412.         if($devolveEntidades){ return $pedidos; }
  2413.         
  2414.         return count($pedidos);
  2415.     }
  2416.     
  2417.     
  2418.     /**
  2419.      * @Route("/app-externo/produtos-pendentes-nao-aceitos-pela-pollo", name="getTotalPedidosNaoAceitosComEntregaPelaPollo", methods={"GET"})
  2420.      */
  2421.     public function getTotalPedidosNaoAceitosComEntregaPelaPolloAction(Request $request): Response
  2422.     
  2423.         $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->getTotalPedidosNaoAceitosComEntregaPelaPollo();
  2424.         $codigos = [];
  2425.         
  2426.         foreach ($pedidos as $pedido){
  2427.             $codigos[] = ($pedido->getPedido()) ? $pedido->getPedido() : $pedido->getNotaFiscal();
  2428.         }
  2429.         return new JsonResponse(['total'=>count($pedidos), 'codigos'=>join(' - '$codigos)], 200);
  2430.     }
  2431.     
  2432.     
  2433.     /**
  2434.      * @Route("/app-externo/busca-avancada", name="busca_avancada", methods={"POST"})
  2435.      */
  2436.     public function buscaAvancada(Request $request): Response
  2437.     
  2438.         $data json_decode($request->getContent(), false);
  2439.         $pedidosData = [];
  2440.         $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilterAdvanced($data);
  2441.         
  2442.         foreach ($pedidos as $pedido) {
  2443.             
  2444.             $pedidoNumero = empty($pedido->getPedido()) ? $pedido->getNotaFiscal() : $pedido->getPedido();
  2445.             
  2446.             $pedidosData[] = ['id'=>$pedido->getId(), 'pedido'=>$pedidoNumero'nome' => $pedido->getContato()];
  2447.         }
  2448.         
  2449.         return new JsonResponse($pedidosData200);
  2450.     }
  2451.     
  2452.     ############# CHAT
  2453.     
  2454.     /**
  2455.      * @Route("/app-externo/chat/lida", name="mensagem_lida", methods={"POST"})
  2456.      */
  2457.     public function lerMensagemChat(Request $request): Response
  2458.     
  2459.         $data json_decode($request->getContent(), false);
  2460.         $user $this->getUser();
  2461.         $mensageEntity $this->getDoctrine()->getRepository(MensagemMural::class)->find($data->mensagem);
  2462.         
  2463.         if($mensageEntity->getIsTodosLer()){
  2464.             if($mensageEntity->getDestinatarioTodos()=='' || $mensageEntity->getDestinatarioTodos()==null){
  2465.                 $mensageEntity->setDestinatarioTodos($user->getEmail());
  2466.             } else {
  2467.                 $todosLido explode(','$mensageEntity->getDestinatarioTodos());
  2468.                 $todosLido[] = $user->getEmail();
  2469.                 $todosLido implode(',',$todosLido);
  2470.                 $mensageEntity->setDestinatarioTodos($todosLido);  
  2471.             }
  2472.         } else {
  2473.             
  2474.             if($mensageEntity->getDestinatario()->getId()!=$user->getId()){
  2475.                 return new JsonResponse([], 400);
  2476.             }
  2477.         
  2478.             $mensageEntity->setIsLida(true);
  2479.             
  2480.         }
  2481.         
  2482.         $this->getDoctrine()->getManager()->flush();
  2483.         
  2484.         return new JsonResponse($this->getAllMensagensChat(), 200);
  2485.     }
  2486.     
  2487.     /**
  2488.      * @Route("/app-externo/cadastro/coleta", name="cadastro_coleta", methods={"POST"})
  2489.      */
  2490.     public function addColeta(Request $request): Response
  2491.     {
  2492.         $data json_decode($request->getContent(), false);
  2493.         $destinatario $this->getDoctrine()->getRepository(User::class)->find($data->destinatario);
  2494.         
  2495.         $mensagem = (new MensagemColeta)
  2496.         ->setTexto($data->mensagem)
  2497.         ->setDestinatario($destinatario)
  2498.         ->setCreatedAt(new \DateTime())
  2499.         ->setIsLida(false)
  2500.         ->setPedido('nenhum');
  2501.         
  2502.         $this->getDoctrine()->getManager()->persist($mensagem);
  2503.         $this->getDoctrine()->getManager()->flush();
  2504.         $messageBody "Solicitação de coleta de mercadoria:\\n\\n" $data->mensagem;
  2505.         $this->sendMensagemViaWhatsapp("text"$destinatario->getTelefone(), $messageBodynullnullnull);
  2506.         //$this->sendMensagemViaWhatsapp("text", '5562991089053', $messageBody, null, null, null);
  2507.         return new JsonResponse([], 200);
  2508.     }
  2509.     
  2510.     /**
  2511.      * @Route("/app-externo/usuarios/coleta/ler", name="ler_mensagem_coleta", methods={"POST"})
  2512.      */
  2513.     public function lerMensagemColeta(Request $request): Response
  2514.     {
  2515.         $data json_decode($request->getContent(), false);
  2516.         $mensagem $this->getDoctrine()->getRepository(MensagemColeta::class)->find($data->id);
  2517.         
  2518.         if($mensagem->getDestinatario()->getId() != $this->getUser()->getId()){
  2519.             return new JsonResponse([], 401);
  2520.         }
  2521.         
  2522.         $mensagem->setIsLida(true);
  2523.         $this->getDoctrine()->getManager()->flush();
  2524.         
  2525.         $messageBody "Mercadoria coletada com sucesso - Separador: *".$this->getUser()->getNome()."*:\\n\\n" $mensagem->getTexto();
  2526.         $this->sendMensagemViaWhatsapp("text"'5562991089053'$messageBodynullnullnull);
  2527.             
  2528.         return new JsonResponse([], 200);
  2529.     }
  2530.     
  2531.     /**
  2532.      * @Route("/app-externo/usuarios/coleta/lista", name="lista_mensagens_coleta", methods={"GET"})
  2533.      */
  2534.     public function mensagensColeta(Request $request): Response
  2535.     {
  2536.         $mensagensData = [];
  2537.         
  2538.         if($this->getIsAdmin()) {
  2539.             $mensagens $this->getDoctrine()->getRepository(MensagemColeta::class)->findBy([],['isLida'=>'ASC''createdAt'=>'DESC']);
  2540.         } else {
  2541.             $mensagens $this->getDoctrine()->getRepository(MensagemColeta::class)->findBy(['destinatario'=>$this->getUser()], ['isLida'=>'ASC''createdAt'=>'DESC']);
  2542.         }
  2543.         
  2544.         $haveIsNaoLida false;
  2545.         foreach ($mensagens as $mensagem) {
  2546.             
  2547.             if(!$mensagem->getIsLida()){
  2548.                 $haveIsNaoLida true;
  2549.             }
  2550.             
  2551.             $mensagensData[] = [
  2552.                 'id'            => $mensagem->getId(),
  2553.                 'destinatario'  => ($mensagem->getDestinatario()) ? $mensagem->getDestinatario()->getNome() : 'não informado',
  2554.                 'mensagem'      => $mensagem->getTexto(),
  2555.                 'pedido'        => $mensagem->getPedido(),
  2556.                 'isLida'        => $mensagem->getIsLida(),
  2557.                 'data'          => $mensagem->getCreatedAt()->format('d/m/Y H:i')
  2558.             ];
  2559.             
  2560.         }
  2561.         
  2562.         return new JsonResponse(['mensagens'=>$mensagensData'haveIsNaoLida'=>$haveIsNaoLida], 200);
  2563.         
  2564.     }
  2565.     
  2566.     /**
  2567.      * @Route("/app-externo/usuarios/coleta", name="list_usuarios_coleta", methods={"GET"})
  2568.      */
  2569.     public function usersColeta(Request $request): Response
  2570.     {
  2571.         $dataRes = [];
  2572.                 
  2573.         $userLogado $this->getUser();
  2574.         $users $this->getDoctrine()->getRepository(User::class)->findAll();
  2575.         
  2576.         foreach ($users as $user) {
  2577.             
  2578.             if($user->getId()!=$userLogado->getId() && in_array('ROLE_ENTREGADOR'$user->getRoles())){
  2579.                 $dataRes[] = [
  2580.                     'value' => $user->getId(),
  2581.                     'text' => $user->getNome(),
  2582.                 ];
  2583.             }
  2584.             
  2585.         }
  2586.         
  2587.         return new JsonResponse($dataRes200); 
  2588.     }
  2589.     
  2590.     /**
  2591.      * @Route("/app-externo/chat/usuarios", name="list_usuarios_chat", methods={"GET"})
  2592.      */
  2593.     public function usersChat(Request $request): Response
  2594.     {
  2595.         $dataRes = [];
  2596.         
  2597.         $dataRes[] = [
  2598.             'value' => 'todos',
  2599.             'text' => 'Todos',
  2600.         ];
  2601.         
  2602.         $dataRes[] = [
  2603.             'value' => 'todos_read',
  2604.             'text' => 'Todos com Leitura',
  2605.         ];
  2606.                 
  2607.         $userLogado $this->getUser();
  2608.         $users $this->getDoctrine()->getRepository(User::class)->findAll();
  2609.         
  2610.         foreach ($users as $user) {
  2611.             if($user->getId()!=$userLogado->getId()){
  2612.                 $dataRes[] = [
  2613.                     'value' => $user->getEmail(),
  2614.                     'text' => $user->getNome(),
  2615.                 ];
  2616.             }
  2617.         }
  2618.         
  2619.         return new JsonResponse($dataRes200); 
  2620.     }
  2621.     /**
  2622.      * @Route("/app-externo/chat/post", name="post_mensagem", methods={"POST"})
  2623.      */
  2624.     public function addMensagemChat(Request $request): Response
  2625.     
  2626.         $data json_decode($request->getContent(), false);
  2627.         $user $this->getUser();
  2628.         
  2629.         if(empty($data->mensagem)){
  2630.             return new JsonResponse($this->getPedidosNaoLidos(), 400); 
  2631.         }
  2632.         
  2633.         $todosLer = ($data->destinatario=='todos_read') ? true false;
  2634.         
  2635.         $mensagem = (new MensagemMural())
  2636.                     ->setMensagem($data->mensagem)
  2637.                     ->setUsuario($user)
  2638.                     ->setCreatedAt(new \DateTime('now'))
  2639.                     ->setIsPrivate($data->isPrivado)
  2640.                     ->setIsTodosLer($todosLer)
  2641.                     ;
  2642.                     
  2643.         if($data->destinatario!='todos' && $data->destinatario!='todos_read'){
  2644.             $userDestinatario $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->destinatario]);
  2645.             $mensagem->setDestinatario($userDestinatario);
  2646.             
  2647.             $messageBody "Nova mensagem no mural do app:\n\n" $data->mensagem;
  2648.             $this->sendMensagemViaWhatsapp("text"$userDestinatario->getTelefone(), $messageBodynullnullnull);
  2649.         }
  2650.         
  2651.         if($data->destinatario=='todos_read'){
  2652.             $userDestinatarios $this->getDoctrine()->getRepository(User::class)->findBy(['zapIsHabilitado'=>true]);
  2653.             $remetente $user->getNome();
  2654.             foreach ($userDestinatarios as $userDestinatario){
  2655.                 if($userDestinatario->getEmail()!=$user->getEmail()){
  2656.                     $messageBody "Nova mensagem no mural do app:\n\nRemetente: $remetente\n\n" $data->mensagem;
  2657.                     $this->sendMensagemViaWhatsapp("text"$userDestinatario->getTelefone(), $messageBodynullnullnull);
  2658.                 }
  2659.             }
  2660.         }
  2661.         
  2662.         if($data->isPrivado) {
  2663.             
  2664.             $remetente $user->getNome();
  2665.             $messageBody "Nova mensagem privada no mural do app:\n\n*Remetente:* $remetente\n\n" $data->mensagem;
  2666.             
  2667.             //$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // Benjamim
  2668.             //$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
  2669.             $this->sendMensagemViaWhatsapp("text""556291089053"$messageBodynullnullnull); // Bruno
  2670.             //$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
  2671.         }
  2672.         
  2673.                     
  2674.         $this->getDoctrine()->getManager()->persist($mensagem);
  2675.         $this->getDoctrine()->getManager()->flush();
  2676.         
  2677.         return new JsonResponse($this->getAllMensagensChat(), 200);
  2678.         
  2679.     }
  2680.     
  2681.     /**
  2682.      * @Route("/app-externo/chat/list/all", name="list_all", methods={"GET"})
  2683.      */
  2684.     public function listAllMensagemChat(Request $request): Response
  2685.     
  2686.         return new JsonResponse($this->getAllMensagensChat(), 200);
  2687.     }
  2688.     
  2689.     /**
  2690.      * @Route("/app-externo/chat/delete", name="delete_mensagem_chat", methods={"POST"})
  2691.      */
  2692.     public function deleteMensagemChat(Request $request): Response
  2693.     
  2694.         $data json_decode($request->getContent(), false);
  2695.         $user $this->getUser();
  2696.         $mensageEntity $this->getDoctrine()->getRepository(MensagemMural::class)->find($data->id);
  2697.         
  2698.         if(!$this->getIsAdmin() && $mensageEntity->getUsuario()->getId() != $user->getId()){
  2699.             return new JsonResponse([], 400);
  2700.         }
  2701.         
  2702.         $this->getDoctrine()->getManager()->remove($mensageEntity);
  2703.         $this->getDoctrine()->getManager()->flush();
  2704.         
  2705.         return new JsonResponse($this->getAllMensagensChat(), 200);
  2706.     }
  2707.     
  2708.     private function getAllMensagensChat() {
  2709.         
  2710.         $mensagensData = [];
  2711.         
  2712.         $user $this->getUser();
  2713.         $mensagensEntity $this->getDoctrine()->getRepository(MensagemMural::class)->findBy([], ['createdAt'=>'DESC']);
  2714.         
  2715.         if(!$this->getIsAdmin()) {
  2716.             $mensagensEntity $this->getDoctrine()->getRepository(MensagemMural::class)->findBy(['isPrivate'=>false], ['createdAt'=>'DESC']);
  2717.         }
  2718.         foreach($mensagensEntity as $mensagemItem) {
  2719.             
  2720.             $nome '';
  2721.             if($mensagemItem->getUsuario() instanceof User && $user instanceof User){
  2722.                 $nome = ($mensagemItem->getUsuario()->getId() == $user->getId()) ? 'Eu' $mensagemItem->getUsuario()->getNome();
  2723.             }
  2724.             
  2725.             $isLida true;
  2726.             $souDestinatario false;
  2727.             // Tem destinatario
  2728.             if($mensagemItem->getDestinatario()!=null && $mensagemItem->getDestinatario()!=''){
  2729.                 // Destinatário não é o usuário logado
  2730.                 if($mensagemItem->getDestinatario()->getId()==$user->getId()){
  2731.                     
  2732.                     $isLida $mensagemItem->getIsLida();
  2733.                     $souDestinatario true;
  2734.                     
  2735.                     $mensagensData[] = [
  2736.                         'id'            => $mensagemItem->getId(),
  2737.                         'mensagem'      => $mensagemItem->getMensagem(),
  2738.                         'data'          => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
  2739.                         'user'          => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
  2740.                         'isPrivate'     => $mensagemItem->getIsPrivate(),
  2741.                         'isOwner'       => ($mensagemItem->getUsuario()->getId() == $user->getId()),
  2742.                         'isLida'        => $isLida,
  2743.                         'lidaOriginal'  => $mensagemItem->getIsLida(), // Para admin controlar
  2744.                         'isMim'         => $souDestinatario,
  2745.                         'destinatario'  => true,
  2746.                         'destNome'      => $mensagemItem->getDestinatario()->getNome(),
  2747.                         'todosLer'      => false,
  2748.                         'souRemetente'  => ($nome=='Eu') ? true false,
  2749.                         'quemLeu'       => $mensagemItem->getDestinatarioTodos()
  2750.                     ];
  2751.                     
  2752.                 } else {
  2753.                     if($this->getIsAdmin()){
  2754.                         $isLida $mensagemItem->getIsLida();
  2755.                         $souDestinatario false;
  2756.                         
  2757.                         $mensagensData[] = [
  2758.                             'id'            => $mensagemItem->getId(),
  2759.                             'mensagem'      => $mensagemItem->getMensagem(),
  2760.                             'data'          => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
  2761.                             'user'          => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
  2762.                             'isPrivate'     => $mensagemItem->getIsPrivate(),
  2763.                             'isOwner'       => ($mensagemItem->getUsuario()->getId() == $user->getId()),
  2764.                             'isLida'        => $isLida,
  2765.                             'lidaOriginal'  => $mensagemItem->getIsLida(), // Para admin controlar
  2766.                             'isMim'         => $souDestinatario,
  2767.                             'destinatario'  => true,
  2768.                             'destNome'      => '',
  2769.                             'todosLer'      => false,
  2770.                             'souRemetente'  => ($nome=='Eu') ? true false,
  2771.                             'quemLeu'       => $mensagemItem->getDestinatarioTodos()
  2772.                         ];
  2773.                     }
  2774.                 }
  2775.             } else {
  2776.                 
  2777.                 // Mensagem para todos lerem
  2778.                 if($mensagemItem->getIsTodosLer()){
  2779.                     
  2780.                     $isLida = (strpos($mensagemItem->getDestinatarioTodos(), $user->getEmail())===false) ? false true;
  2781.                     
  2782.                     $lidaOriginal true;
  2783.                     $userDestinatarios $this->getDoctrine()->getRepository(User::class)->findBy(['zapIsHabilitado'=>true]);
  2784.                     
  2785.                     foreach ($userDestinatarios as $userDestinatario){
  2786.                         if($userDestinatario->getId()!=$user->getId()){
  2787.                             $usuarioNaoLocalizado $user->getEmail();
  2788.                             // Este usuário não consta na lista
  2789.                             if(!strpos($mensagemItem->getDestinatarioTodos(), $user->getEmail())){
  2790.                                 $lidaOriginal false;
  2791.                                 break;
  2792.                             }
  2793.                         }
  2794.                     }
  2795.                     
  2796.                     $souDestinatario false;
  2797.                     $mensagensData[] = [
  2798.                         'id'            => $mensagemItem->getId(),
  2799.                         'mensagem'      => $mensagemItem->getMensagem(),
  2800.                         'data'          => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
  2801.                         'user'          => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
  2802.                         'isPrivate'     => $mensagemItem->getIsPrivate(),
  2803.                         'isOwner'       => ($mensagemItem->getUsuario()->getId() == $user->getId()),
  2804.                         'isLida'        => $isLida,
  2805.                         'lidaOriginal'  => $lidaOriginal// Para admin controlar
  2806.                         'isMim'         => $souDestinatario,
  2807.                         'destinatario'  => false,
  2808.                         'destNome'      => '',
  2809.                         'todosLer'      => true,
  2810.                         'souRemetente'  => ($nome=='Eu') ? true false,
  2811.                         'quemLeu'       => $mensagemItem->getDestinatarioTodos()
  2812.                     ];
  2813.                     
  2814.                 } else {
  2815.                     
  2816.                     $isOwner false;
  2817.                     
  2818.                     if($user instanceof User){
  2819.                         $isOwner = ($mensagemItem->getUsuario()->getId() == $user->getId());
  2820.                     }
  2821.                     
  2822.                     $souDestinatario false;
  2823.                     $mensagensData[] = [
  2824.                         'id'            => $mensagemItem->getId(),
  2825.                         'mensagem'      => $mensagemItem->getMensagem(),
  2826.                         'data'          => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
  2827.                         'user'          => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
  2828.                         'isPrivate'     => $mensagemItem->getIsPrivate(),
  2829.                         'isOwner'       => $isOwner,
  2830.                         'isLida'        => $isLida,
  2831.                         'lidaOriginal'  => $mensagemItem->getIsLida(), // Para admin controlar
  2832.                         'isMim'         => $souDestinatario,
  2833.                         'destinatario'  => false,
  2834.                         'destNome'      => '',
  2835.                         'todosLer'      => false,
  2836.                         'souRemetente'  => ($nome=='Eu') ? true false,
  2837.                         'quemLeu'       => $mensagemItem->getDestinatarioTodos()
  2838.                     ];
  2839.                     
  2840.                 }
  2841.             }
  2842.   
  2843.         }
  2844.         
  2845.         return array_slice($mensagensData030);
  2846.     }
  2847.     
  2848.     ############# CHAT
  2849.     
  2850.     private function getFaturamentoAtual() {
  2851.         
  2852.         // $faturamentoAtual = 0;
  2853.         
  2854.         // $jsonFile = '/www/wwwroot/gestor.moveispollo.com.br/db_local.json';
  2855.         // $jsonData = file_get_contents($jsonFile);
  2856.         // $data = json_decode($jsonData, true);
  2857.         
  2858.         // $faturamentoAtual = $data['total'];
  2859.         
  2860.         $total $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtual();
  2861.         return $total;
  2862.     }
  2863.     
  2864.     /**
  2865.      * @Route("/app-externo-socket", name="app_externo_socket")
  2866.      */
  2867.     public function indexSocket(Request $request): Response
  2868.     {
  2869.         return $this->render('app_externo/index-socket.html.twig');
  2870.     }
  2871.     
  2872.     /**
  2873.      * @Route("/app-externo", name="app_externo")
  2874.      */
  2875.     public function index(Request $request): Response
  2876.     {
  2877.         
  2878.         $abrePedidoParaCadastro 'false';
  2879.         if($request->get('add_card')){
  2880.             $abrePedidoParaCadastro 'true';
  2881.         }
  2882.         
  2883.         $pedidosAgendados $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosAgendados();
  2884.         $pedidosAgendadosData = [];
  2885.         foreach ($pedidosAgendados as $pedidoAgendado) {
  2886.             
  2887.             if($pedidoAgendado->getMeioEntrega()=='Pela Pollo Móveis' || $pedidoAgendado->getMeioEntrega()=='Viagem pela Pollo Móveis'){
  2888.                 
  2889.                 $pedidosAgendadosData[] = $pedidoAgendado->getDataEntrega()->format('d/m/y');
  2890.                 
  2891.             }
  2892.         }
  2893.         
  2894.         $hoje = new \DateTime();
  2895.         
  2896.         // Conta o número de ocorrências de cada data
  2897.         $contagem array_count_values($pedidosAgendadosData);
  2898.         
  2899.         // Filtra as datas que aparecem mais de três vezes
  2900.         $datas_repetidas array_filter($contagem, function($valor) {
  2901.             $hoje = new \DateTime();
  2902.             return $valor $this->getTotalPedidosDia($hoje);
  2903.         });
  2904.         
  2905.         // Extrai as chaves do array resultante
  2906.         $datas_mais_de_3_vezes array_keys($datas_repetidas);
  2907.         
  2908.         // Adicione aspas simples a cada data no array PHP
  2909.         $datas_desativadas_array array_map(function($data) {
  2910.             return "'" trim($data) . "'";
  2911.         }, $datas_mais_de_3_vezes);
  2912.         
  2913.         // Converta o array PHP de volta para uma string separada por vírgulas
  2914.         $datas_desativadas_string implode(','$datas_desativadas_array);
  2915.         
  2916.         $ultimoDiaMes = clone $hoje;
  2917.         $ultimoDiaMes->modify('first day of next month');
  2918.         $ultimoDiaMes->modify('-1 day');
  2919.         return $this->render('app_externo/index-v2.html.twig', [
  2920.             'controller_name' => 'AppExternoController',
  2921.             'usario' => $this->getUser()->getEmail(),
  2922.             'isAdmin' => $this->getIsAdmin(),
  2923.             'isEntregador' => $this->getIsEntregador(),
  2924.             'isEntregadorAux' => $this->getIsEntregadorAux(),
  2925.             'isVendedor' => $this->getIsVendedor(),
  2926.             'isSeparador' => $this->getIsSeparador(),
  2927.             'menuContextoCard' => $this->getMenuContextoCard(),
  2928.             'dataHoje' => $hoje->format('Y-m-d'),
  2929.             // 'faturamentoAtual' => __DIR__,
  2930.             'faturamentoAtual' => number_format($this->getFaturamentoAtual(), 2',''.'),
  2931.             'abreNovoPedido' => $abrePedidoParaCadastro,
  2932.             'pedidoNovoParaAdd' => $request->get('add_card'),
  2933.             'temAlgumValePendente' => $this->temAlgumValePendente(),
  2934.             'primeiro_dia_mes' => $hoje->format('Y') . '-'.$hoje->format('m').'-01',
  2935.             'ultimo_dia_mes' => $ultimoDiaMes->format('Y-m-d'),
  2936.             'datas_pedidos_agendados' => $datas_desativadas_string,
  2937.             'total_pedidos_liberados_hoje' => 10,
  2938.             'pode_abrir_modal_pedidos_pendentes_cadastro' => true
  2939.         ]);
  2940.  
  2941.     }
  2942.     
  2943.     /**
  2944.      * @Route("/app-externo/periodos-disponiveis-entrega", name="app_externo_pedidos_disponiveis_entrega", methods={"POST"})
  2945.      */
  2946.     public function getPeriodosDisponiveisEntregaNaData(Request $request): Response
  2947.     {
  2948.         $data json_decode($request->getContent(), false);
  2949.         
  2950.         if(!isset($data->data)){
  2951.             return new JsonResponse([
  2952.                 ['value'=>'De Manhã''text'=>'De Manhã'],
  2953.                 ['value'=>'À tarde''text'=>'À tarde'],
  2954.                 ['value'=>'Qualquer horário''text'=>'Qualquer horário'],
  2955.             ], 200); 
  2956.         }
  2957.         
  2958.         if($data->data=='' || $data->data=='Não informado'){
  2959.             return new JsonResponse([
  2960.                 ['value'=>'De Manhã''text'=>'De Manhã'],
  2961.                 ['value'=>'À tarde''text'=>'À tarde'],
  2962.                 ['value'=>'Qualquer horário''text'=>'Qualquer horário'],
  2963.             ], 200);
  2964.         }
  2965.         
  2966.         $date = \DateTime::createFromFormat('d/m/Y'$data->data);
  2967.         $hoje = new \DateTime('now');
  2968.         $dataInicio $date->format('Y-m-d');
  2969.         
  2970.         $pedidosAgendados $this->getDoctrine()
  2971.         ->getRepository(EntregaPedido::class)
  2972.         ->getPedidosAgendadosNaData($dataInicio$dataInicionull);
  2973.         
  2974.         $totalPedidosAgendadosSemViagem 0;
  2975.         foreach ($pedidosAgendados as $pedidoAgendado) {
  2976.             if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
  2977.                 $totalPedidosAgendadosSemViagem++;
  2978.             }
  2979.         }
  2980.         
  2981.         $totalPedidosManha 0;
  2982.         $totalPedidosTarde 0;
  2983.         $totalPedidosQualquerHorario 0;
  2984.         $totalPedidosDia $this->getTotalPedidosDia($date); // 24 pedidos por dia
  2985.         
  2986.         
  2987.         $totalPedidosNaDataManha $this->getDoctrine()->getRepository(EntregaPedido::class)
  2988.                                     ->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), 'De Manhã');
  2989.         $totalPedidosNaDataManha count($totalPedidosNaDataManha);
  2990.         
  2991.         $totalPedidosNaDataManha = ($totalPedidosDia/2) - $totalPedidosNaDataManha;
  2992.         
  2993.         
  2994.         $totalPedidosNaDataTarde $this->getDoctrine()->getRepository(EntregaPedido::class)
  2995.                                    ->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), 'À tarde');
  2996.         $totalPedidosNaDataTarde count($totalPedidosNaDataTarde);
  2997.         
  2998.         $totalPedidosNaDataTarde = ($totalPedidosDia/2) - $totalPedidosNaDataTarde;
  2999.     
  3000.         $totalPedidosNaDataQualquerHorario $this->getDoctrine()->getRepository(EntregaPedido::class)
  3001.                                    ->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), 'Qualquer horário');
  3002.         $totalPedidosNaDataQualquerHorarioTotal count($totalPedidosNaDataQualquerHorario);
  3003.         
  3004.         $totalPedidosNaDataQualquerHorario = ($totalPedidosDia-($totalPedidosNaDataManha+$totalPedidosNaDataTarde));
  3005.         $totalPedidosNaDataQualquerHorario $totalPedidosNaDataQualquerHorario+$totalPedidosNaDataQualquerHorarioTotal;
  3006.         $totalPedidosNaDataQualquerHorario $totalPedidosDia-$totalPedidosNaDataQualquerHorario;
  3007.         $periodosNovo = [];
  3008.         
  3009.         if(ceil($totalPedidosNaDataManha)>0) {
  3010.             $periodosNovo[] = ['value'=>'De Manhã''text'=>'De Manhã('.ceil($totalPedidosNaDataManha).')'];
  3011.         } else {
  3012.             $periodosNovo[] = ['value'=>'lotado''text'=>'De Manhã('.ceil($totalPedidosNaDataManha).')'];
  3013.         }
  3014.         
  3015.         if(ceil($totalPedidosNaDataTarde)>0) {
  3016.             $periodosNovo[] = ['value'=>'À Tarde''text'=>'À Tarde('.ceil($totalPedidosNaDataTarde).')'];
  3017.         } else {
  3018.             $periodosNovo[] = ['value'=>'lotado''text'=>'À Tarde('.ceil($totalPedidosNaDataTarde).')'];
  3019.         }
  3020.         
  3021.         // if(ceil($totalPedidosNaDataQualquerHorario)>0){
  3022.         //     $periodosNovo[] = ['value'=>'Qualquer horário', 'text'=>'Qualquer horário('.ceil($totalPedidosNaDataQualquerHorario).')'];
  3023.         // } else {
  3024.         //     $periodosNovo[] = ['value'=>'lotado', 'text'=>'Qualquer horário('.ceil($totalPedidosNaDataQualquerHorario).')'];
  3025.         // }
  3026.         
  3027.         // echo "Manha: $totalPedidosNaDataManha - Tarde: $totalPedidosNaDataTarde - Qualquer: $totalPedidosNaDataQualquerHorario - Por dia: $totalPedidosDia";
  3028.         // exit;
  3029.         
  3030.         $totalPedidosNaData $totalPedidosAgendadosSemViagem// 10 pedidos
  3031.         
  3032.         $pedidosManha = [];
  3033.         $pedidosTarde = [];
  3034.         $pedidosNumeros = [];
  3035.         foreach ($pedidosAgendados as $pedidoAgendado) {
  3036.             
  3037.             // verifica se este pedido está com data de entrega anterior a hoje
  3038.             if($pedidoAgendado->getEntregarAt() instanceof \DateTime){
  3039.                 if($dataInicio $pedidoAgendado->getEntregarAt()->format('Y-m-d')){
  3040.                     continue;
  3041.                 }
  3042.             }
  3043.             
  3044.             $pedidosNumeros[] = ($pedidoAgendado->getPedido()!='') ? $pedidoAgendado->getPedido() : $pedidoAgendado->getNotaFiscal();
  3045.             
  3046.            if($pedidoAgendado->getPeriodoEntrega()=='Qualquer horário'){
  3047.                
  3048.                //if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
  3049.                    $totalPedidosQualquerHorario++;
  3050.               // }
  3051.                
  3052.            } else if($pedidoAgendado->getPeriodoEntrega()=='De Manhã') {
  3053.                
  3054.                //if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
  3055.                     $totalPedidosManha++;
  3056.                //}
  3057.                
  3058.                $pedidosManha[] = ($pedidoAgendado->getPedido()!='' && $pedidoAgendado->getPedido()!=null) ? $pedidoAgendado->getPedido() : $pedidoAgendado->getNotaFiscal();
  3059.            } else if($pedidoAgendado->getPeriodoEntrega()=='À tarde') {
  3060.                
  3061.                //if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
  3062.                     $totalPedidosTarde++;
  3063.                //}
  3064.                
  3065.                $pedidosTarde[] = ($pedidoAgendado->getPedido()!='' && $pedidoAgendado->getPedido()!=null) ? $pedidoAgendado->getPedido() : $pedidoAgendado->getNotaFiscal();
  3066.            }
  3067.         }
  3068.         
  3069.         //$totalPedidosDisponiveisParaEntrega = $totalPedidosDia - $totalPedidosNaData - $totalPedidosQualquerHorario;
  3070.         
  3071.         $totalPedidosDisponiveisParaEntrega $totalPedidosDia $totalPedidosNaData;
  3072.         
  3073.         //$totalPedidosDisponiveisParaEntrega = $totalPedidosDia - ($totalPedidosManha+$totalPedidosTarde+$totalPedidosQualquerHorario);
  3074.         $totalPedidosParaManha $totalPedidosDisponiveisParaEntrega $totalPedidosNaDataManha// 12 pedidos
  3075.         //$totalPedidosParaManha = $totalPedidosParaManha - $totalPedidosManha;
  3076.         
  3077.         $totalPedidosParaTarde $totalPedidosDisponiveisParaEntrega $totalPedidosNaDataTarde// 12 pedidos
  3078.         //$totalPedidosParaTarde = $totalPedidosParaTarde - $totalPedidosTarde;
  3079.        
  3080.        
  3081.        $periodos = [];
  3082.        
  3083.        $pedidosManha implode(',',$pedidosManha);
  3084.        $pedidosTarde implode(',',$pedidosTarde);
  3085.         if($totalPedidosParaManha>0) {
  3086.             
  3087.             $dataDesejada $date->format('Y-m-d');
  3088.             $dataHoje $hoje->format('Y-m-d');
  3089.             
  3090.             if($dataDesejada==$dataHoje) {
  3091.                 $hour = (int)$hoje->format('H');
  3092.                 if($hour<=11) {
  3093.                     //$periodos[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.$totalPedidosParaManha.') P:'.$pedidosManha];
  3094.                     $periodos[] = ['value'=>'De Manhã''text'=>'De Manhã('.ceil($totalPedidosParaManha).')'];
  3095.                 }
  3096.             } else {
  3097.                 //$periodos[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.$totalPedidosParaManha.') P:'.$pedidosManha];
  3098.                 $periodos[] = ['value'=>'De Manhã''text'=>'De Manhã('.ceil($totalPedidosParaManha).')'];
  3099.             }
  3100.             
  3101.         }
  3102.         
  3103.         if($totalPedidosParaTarde>0) {
  3104.             //$periodos[] = ['value'=>'À tarde', 'text'=>'À tarde('.$totalPedidosParaTarde.') P:'.$pedidosTarde];
  3105.             $periodos[] = ['value'=>'À tarde''text'=>'À tarde('.ceil($totalPedidosParaTarde).')'];
  3106.         }
  3107.         if(($totalPedidosParaManha>0) && ($totalPedidosParaTarde>0)) {
  3108.             $totalDisponivelNoDia ceil($totalPedidosParaManha)+ceil($totalPedidosParaTarde);
  3109.             $periodos[] = ['value'=>'Qualquer horário''text'=>'Qualquer horário('.$totalDisponivelNoDia.')'];
  3110.         }
  3111.         
  3112.         $periodos[] = ['value'=>'''text'=>''];
  3113.         
  3114.         
  3115.         
  3116.         
  3117.         
  3118.         
  3119.         
  3120.         
  3121.         $pedidosNumeros join(', '$pedidosNumeros);
  3122.         
  3123.         return new JsonResponse(['periodos'=>$periodosNovo'pedidos'=>$pedidosNumeros'totalPedidosNaData'=>$totalPedidosNaData'totalPedidosDia'=>$totalPedidosDia], 200); 
  3124.     }
  3125.     
  3126.     public function getMenuContextoCard() {
  3127.         return '<a style="position:absolute;right:10px;top:10px;" data-toggle="modal" data-target="#modal-problema-pedido" @click="alert();idCurrentPedido = pedidoTansito.id">
  3128.                     <i class="fa fa-bars" aria-hidden="true" style="color:orange; font-size:30px;"></i>
  3129.                 </a>';
  3130.     }
  3131.     
  3132.     /**
  3133.      * @Route("/app-externo/ler-obs-pendente-de-leitura", name="pedidos_pendente_leitura_lida", methods={"POST"})
  3134.      */
  3135.     public function pedidosPendentesLeituraLido(Request $request): Response
  3136.     {  
  3137.         $data json_decode($request->getContent(), false);
  3138.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  3139.         
  3140.         if($pedido instanceof EntregaPedido){
  3141.             $pedido->setIsObsLida(true);
  3142.             $this->getDoctrine()->getManager()->flush();
  3143.         }
  3144.         
  3145.         return new JsonResponse(['pedidosLidos'=>$this->getPedidosNaoLidos()], 200); 
  3146.     }
  3147.     
  3148.     /**
  3149.      * @Route("/app-externo/busca-pedidos-com-obs-pendente-de-leitura", name="pedidos_pendente_leitura", methods={"GET"})
  3150.      */
  3151.     public function pedidosPendentesLeitura(Request $request): Response
  3152.     {  
  3153.         return new JsonResponse($this->getPedidosNaoLidos(), 200); 
  3154.     }
  3155.     
  3156.     private function getPedidosNaoLidos() {
  3157.         $pedidosResult = [];
  3158.         
  3159.         $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['isObsLida'=>false], array('id' => 'DESC'));
  3160.         foreach ($pedidos as $pedido) {
  3161.             $pedidosResult[] = ['id'=>$pedido->getId(), 'pedido'=>$pedido->getPedido(),'nf'=>$pedido->getNotaFiscal()];
  3162.         }
  3163.         
  3164.         return $pedidosResult;
  3165.     }
  3166.     
  3167.     /**
  3168.      * @Route("/app-externo/busca-pedido-filter", name="busca_pedido_filter", methods={"POST"})
  3169.      */
  3170.     public function buscaPedidoFilter(Request $request): Response
  3171.     {   
  3172.         $data json_decode($request->getContent(), false);
  3173.         // // Tipo Filtro = $data->field
  3174.         // // Valor: $data->value        
  3175.         // $pedidosResult = [];
  3176.         // $pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilter($data->field, $data->value);
  3177.         
  3178.         // $pedidosResult = $this->todosPedidosPorStatus();
  3179.         
  3180.         // foreach ($pedidos as $pedido) {
  3181.         //     // Se quiser retornar na mesma posição dele na aba. capturar o status e concatenar na posição correta
  3182.         //     $pedidosResult['baixados'][] = $this->makeProdutoData($pedido);
  3183.         // }
  3184.         
  3185.         $pedidosResult $this->todosPedidosPorStatus($data->value$data->fieldtrue$data->tipo);
  3186.         return new JsonResponse($pedidosResult200); 
  3187.         
  3188.     }
  3189.     
  3190.     /**
  3191.      * @Route("/app-externo/geraSenhas", name="geraSenhas")
  3192.      */
  3193.     public function geraSenhas(UserPasswordEncoderInterface $passwordEncoder): Response
  3194.     {
  3195.         
  3196.         $usuarios = [
  3197.             ['nome'=>'kevin''id'=>478976],
  3198.             ['nome'=>'kawan''id'=>98702],
  3199.             ['nome'=>'adriel''id'=>465667]
  3200.         ];
  3201.         
  3202.         foreach ($usuarios as $usuario) {
  3203.             
  3204.             $nome strtolower($usuario['nome']);
  3205.             echo 'Login: ' $nome ' - Senha: ' $usuario['id'] . '<br/>';
  3206.             
  3207.             /** @var User $entity */
  3208.             $entity $this->getDoctrine()->getRepository(User::class)->find(16);
  3209.             $nome strtolower($usuario['nome']);
  3210.             $password $passwordEncoder->encodePassword($entity$usuario['id']);
  3211.             
  3212.             echo $password.'<br/>';
  3213.         }
  3214.         
  3215.         exit();
  3216.         
  3217.     
  3218.         
  3219.         // $usuarios = $this->getDoctrine()->getRepository(User::class)->findAll();
  3220.         // foreach ($usuarios as $usuario) {
  3221.         //     if($usuario->getEmail()!='bruno@moveispollo.com.br' && $usuario->getEmail()!='neto'){
  3222.                 
  3223.         //         $caracteresPermitidos = '0123456789';
  3224.         //         // Gere a senha aleatória
  3225.         //         $senha = '';
  3226.         //         $tamanhoCaracteres = strlen($caracteresPermitidos);
  3227.         //         for ($i = 0; $i < 8; $i++) {
  3228.         //             $senha .= $caracteresPermitidos[rand(0, $tamanhoCaracteres - 1)];
  3229.         //         }
  3230.                 
  3231.         //         $password = $passwordEncoder->encodePassword($usuario, $senha);
  3232.                 
  3233.         //         $usuario->setPassword($password);
  3234.         //         $this->getDoctrine()->getManager()->flush();
  3235.                 
  3236.         //         echo '######################################################<br/>';
  3237.         //         echo $usuario->getNome() . '<br/>';
  3238.         //         echo 'Login: ' . strtolower($usuario->getEmail()) . '<br/>';
  3239.         //         echo 'Senha: ' . $senha . '<br/>';
  3240.     
  3241.         //     }
  3242.         // }
  3243.         
  3244.         // exit();
  3245.     }
  3246.     
  3247.     /**
  3248.      * @Route("/app-externo/enviar-imagem-link-assistencia", name="envia_imagem_por_link_assistencia", methods={"POST"})
  3249.      */
  3250.     public function enviarLinkAssistencia(Request $requestHttpClientInterface $client): Response
  3251.     {
  3252.         $arrContextOptions = array(
  3253.             "ssl" => array(
  3254.                 "verify_peer" => false,
  3255.                 "verify_peer_name" => false,
  3256.             )
  3257.         );
  3258.         
  3259.         $data json_decode($request->getContent(), false);
  3260.         $idPedido $data->pedido;
  3261.         $imageName time();
  3262.         $filename "$imageName.jpeg";
  3263.         $uploadfile '/www/wwwroot/gestor.moveispollo.com.br/public/img_assistencia/'.$filename;
  3264.         
  3265.         $data file_get_contents($data->linkfalsestream_context_create($arrContextOptions));
  3266.         file_put_contents($uploadfile$data);
  3267.             
  3268.         $fotos = [];
  3269.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  3270.         if($pedido->getFotosAssistencia()!='' && $pedido->getFotosAssistencia() !=null){
  3271.             $fotos json_decode($pedido->getFotosAssistencia());
  3272.         }
  3273.         
  3274.         $fotos[] = $filename;
  3275.         $pedido->setFotosAssistencia(json_encode($fotos));
  3276.         $this->getDoctrine()->getManager()->flush();
  3277.         
  3278.         $fotos json_decode($pedido->getFotos());
  3279.         $fotosSinistro json_decode($pedido->getFotosSinistro());
  3280.         $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  3281.         
  3282.         return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$pedido->getNotas(), 'sinistros'=>$fotosSinistro'comprovante'=>$pedido->getComprovantePagamento(), 'fotos_assistencia'=>$fotosAssistencia],$this->todosPedidosPorStatus()), 200);
  3283.     }
  3284.     /**
  3285.      * @Route("/app-externo/pedido-detalhe", name="pedido_detalhe", methods={"GET"})
  3286.      */
  3287.     public function getDetalhePedido(Request $requestHttpClientInterface $client): Response
  3288.     {
  3289.         return $this->render('app_externo/telas/pedido.html.twig');
  3290.     }
  3291.     /**
  3292.      * @Route("/app-externo/aceitacao-separador", name="aeitacao_separador", methods={"POST"})
  3293.      */
  3294.     public function aceitacaoSeparador(Request $requestHttpClientInterface $client): Response
  3295.     {
  3296.         $data json_decode($request->getContent(), false);
  3297.         
  3298.         $user $this->getUser();
  3299.         $idPedido 0;
  3300.         
  3301.         if(isset($data->pedido->id)){
  3302.             $idPedido $data->pedido->id;
  3303.         } else {
  3304.             $idPedido $data->pedido;
  3305.         }
  3306.         
  3307.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  3308.         
  3309.         if(!$pedido instanceof EntregaPedido) {
  3310.             return new JsonResponse([], 400);
  3311.         }
  3312.         
  3313.         $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  3314.         
  3315.         if(!$pedido->getTempoGastoSeparacao()) {
  3316.             
  3317.             // $messageBody = "O Pedido / NF  *$numeroPedido* foi Aceito para *Montagem/Separação* pelo {$user->getNome()}.\n\nCliente: " . $pedido->getContato();
  3318.     
  3319.             // $destinatarios = ['556291089053', '5562994542599'];
  3320.             // foreach ($destinatarios as $destinatario) {
  3321.                 
  3322.             //     // $destino = 'W';
  3323.             //     // if($destinatario=='556232337424') {
  3324.             //     //     $destino = 'B';
  3325.             //     // }
  3326.             
  3327.             //     $this->sendMensagemViaWhatsapp("text", $destinatario, $messageBody, null, null, null, null);
  3328.             // }
  3329.         
  3330.         }
  3331.         
  3332.         
  3333.         $pedido->setSeparadorAceitouAt(new \DateTime('now'));
  3334.         
  3335.         
  3336.         if(isset($data->tempoGastoAceitacao)) {
  3337.             
  3338.             $destinatariosPronto = ['556291089053''556232337424'];
  3339.             
  3340.             if($pedido->getColaboradorUser()){
  3341.                 $telefoneMotorista $pedido->getColaboradorUser()->getTelefone();
  3342.                 $destinatariosPronto[] = $telefoneMotorista;
  3343.             }
  3344.             
  3345.             if($data->tempoGastoAceitacao=='Pronto') {
  3346.                 
  3347.                 $messageBody "A *Montagem/Separação* do Pedido / NF  *$numeroPedido* está *Pronto*.\n\nCliente: " $pedido->getContato();
  3348.                 foreach ($destinatariosPronto as $destinatario) {
  3349.                     $this->sendMensagemViaWhatsapp("text"$destinatario$messageBodynullnullnull);
  3350.                 }
  3351.             }
  3352.             
  3353.             $pedido->setTempoGastoSeparacao($data->tempoGastoAceitacao);
  3354.             
  3355.             if($data->tempoGastoAceitacao!='Até o Fim da Manhã' && $data->tempoGastoAceitacao!='Até o Fim da Tarde' && $data->tempoGastoAceitacao!='Pronto') {
  3356.                 
  3357.                 if($data->tempoGastoAceitacao) {
  3358.                     $time = new \DateTime('now');
  3359.                     $time->add(new \DateInterval('PT' $data->tempoGastoAceitacao 'M'));
  3360.                     $pedido->setPrevisaoDataSeparacaoAt($time);
  3361.                 }
  3362.                 
  3363.             }
  3364.         }
  3365.         
  3366.         if($this->getIsAdmin()) {
  3367.            $pedido->setSeparador($data->pessoa);
  3368.         } else {
  3369.             $pedido->setSeparador($user->getEmail());
  3370.         }
  3371.         
  3372.         //$pedido->setStatus('aceito');
  3373.         
  3374.         $this->getDoctrine()->getManager()->flush();
  3375.     
  3376.         // // Envio zap vendedor
  3377.         // $usuarioVendedor = strtolower($pedido->getVendedor());
  3378.         // $usarioVendedor = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioVendedor]);
  3379.         // if($usarioVendedor instanceof User){
  3380.         //     $telefone = $usarioVendedor->getTelefone();
  3381.             
  3382.         //     $destino = 'W';
  3383.         //     if($telefone=='5562994542599') {
  3384.         //         $destino = 'B';
  3385.         //     }
  3386.         //     $this->sendMensagemViaWhatsapp("text", $telefone, $messageBody, null, null, null, $destino);
  3387.         // }
  3388.         
  3389.         // // Envio zap Cadastrante
  3390.         // $usuarioCadastrante = strtolower($pedido->getCadastradoPor());
  3391.         // $usuarioCadastrante = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioCadastrante]);
  3392.         // if($usuarioCadastrante instanceof User){
  3393.         //     $telefone = $usuarioCadastrante->getTelefone();
  3394.             
  3395.         //     $destino = 'W';
  3396.         //     if($telefone=='5562994542599') {
  3397.         //         $destino = 'B';
  3398.         //     }
  3399.         //     $this->sendMensagemViaWhatsapp("text", $telefone, $messageBody, null, null, null, $destino);
  3400.         // }
  3401.         
  3402.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  3403.         
  3404.     }
  3405.     
  3406.     /**
  3407.      * @Route("/app-externo/update-checkbox-pedido", name="update_checkbox_pedido", methods={"POST"})
  3408.      */
  3409.     public function updateCheckBoxPedido(Request $requestHttpClientInterface $client): Response
  3410.     {
  3411.         $data json_decode($request->getContent(), false);
  3412.         if(!$this->getIsAdmin()){
  3413.             return new JsonResponse(['message'=>'Não é admin'], 400);
  3414.         }
  3415.         
  3416.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido->id);
  3417.         
  3418.         if(!$pedido instanceof EntregaPedido){
  3419.             return new JsonResponse(['message'=>'Pedido não localizado'], 400);
  3420.         }
  3421.         
  3422.         // if($data->check == 'pedidoRealizadoCheck') {
  3423.         //     if(!$pedido->getSolicitarMontagemSaoJose() && !$pedido->getSolicitarSeparacaoSaoJose()) {
  3424.         //         return new JsonResponse(['message'=>'Necessário solicitar montagem/separação antecipadamente.'], 400);
  3425.         //     }
  3426.         // }
  3427.         
  3428.         // if($data->check == 'pedidoRealizadoCoimbraCheck'){
  3429.         //     if(!$pedido->getSolicitarMontagem() && !$pedido->getSolicitarSeparacao()) {
  3430.         //         return new JsonResponse(['message'=>'Necessário solicitar montagem/separação antecipadamente.'], 400);
  3431.         //     }
  3432.         // }
  3433.         
  3434.         $nameMethod ucfirst($data->check);
  3435.         
  3436.         $localidade '';
  3437.         if (strpos($nameMethod'SaoJose') !== false || 
  3438.         $nameMethod=='PedidoMontandoRonald' || 
  3439.         $nameMethod=='PedidoMontandoFabio' || 
  3440.         $nameMethod=='PedidoMontandoRian' || 
  3441.         $nameMethod=='AguardandoColeta' || 
  3442.         $nameMethod=='IsColetado' || 
  3443.         $nameMethod=='SolicitarMontagemSaoJose' || 
  3444.         $nameMethod=='SolicitarSeparacao' || 
  3445.         $nameMethod=='SolicitarSeparacaoSaoJose' || 
  3446.         $nameMethod=='PedidoMontandoMontagemFinalizada') {
  3447.             $nameMethodSet 'set' $nameMethod;
  3448.             $nameMethodGet 'get' $nameMethod
  3449.         } else if($nameMethod=='PedidoImpressoGuilhermeCheck'){
  3450.             $nameMethodSet 'setPedidoImpressoGuilhermeCheck';
  3451.             $nameMethodGet 'getPedidoImpressoGuilhermeCheck'
  3452.         } else if($nameMethod=='SolicitarMontagem') {
  3453.             $nameMethodSet 'set' $nameMethod;
  3454.             $nameMethodGet 'get' $nameMethod
  3455.         } else {
  3456.             $nameMethodSet 'set' $nameMethod 'At';
  3457.             $nameMethodGet 'get' $nameMethod 'At'
  3458.         }
  3459.         
  3460.         
  3461.         // if($nameMethod=='SolicitarMontagemSaoJose' || $nameMethod=='SolicitarSeparacaoSaoJose'){
  3462.         //     $pedido->setLocalidadeSaoJose('sj');
  3463.         // }
  3464.         
  3465.         // if($nameMethod=='SolicitarSeparacao' || $nameMethod=='SolicitarMontagem'){
  3466.         //     $pedido->setLocalidade('co');
  3467.         // }
  3468.         $valueUpdate = new \DateTime('now');
  3469.         $getValue $pedido->{$nameMethodGet}();
  3470.         
  3471.         if($getValue instanceof \DateTime) {
  3472.             $valueUpdate null;
  3473.         }
  3474.         
  3475.         $pedido->{$nameMethodSet}($valueUpdate);
  3476.         
  3477.         $enderecoEntrega = ($pedido->getNovoEnderecoEntrega() != '' && $pedido->getNovoEnderecoEntrega() != null) ? $pedido->getNovoEnderecoEntrega() : $pedido->getEndereco();
  3478.         
  3479.         $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  3480.         
  3481.         switch ($data->check) {
  3482.             case 'pedidoRealizadoCheck':
  3483.                 $pedido->setLastUpdateStatus(new \DateTime('now'));
  3484.                 $pedido->setStatus('recebido');
  3485.                 break;
  3486.                 
  3487.             case 'pedidoRealizadoCoimbraCheck':
  3488.                 $pedido->setLastUpdateStatus(new \DateTime('now'));
  3489.                 $pedido->setStatus('recebido');
  3490.                 break;
  3491.             case 'pedidoImpressoCheck':
  3492.                 // code...
  3493.                 break;
  3494.                 
  3495.             case 'pedidoEnderecoCheck':
  3496.                 //$dadosCliente = $this->getDadosCliente($pedido->getPedido(),$client);
  3497.                 //$messageBody = "*Endereço:* ".$dadosCliente['endereco'];
  3498.                 $messageBody "*Endereço:* " $enderecoEntrega;
  3499.                 $messageImagemBody 'endereco-para-entrega.jpeg';
  3500.                 break;
  3501.                 
  3502.             case 'pedidoMontagemCheck':
  3503.                 $messageBody "*Produtos*: Pré-montagem ou Separação.";
  3504.                 $messageImagemBody 'montando-produtos.jpeg';
  3505.                 break;
  3506.                 
  3507.                 
  3508.             case 'pedidoMotoristaCheck':
  3509.                 // code...
  3510.                 break;
  3511.                 
  3512.             case 'pedidoInstagramCheck':
  3513.                 $messageBody "Ajude a Pollo Móveis seguindo o *Instagram*.\nCupom de desconto para seguidores.\n👉 instagram.com/pollomoveisescritorio\n👉 www.facebook.com/pollomoveisescritorio";
  3514.                 $messageImagemBody 'instagram.jpeg';
  3515.                 break;
  3516.                 
  3517.             case 'pedidoGoogleCheck':
  3518.                 $messageBody "Para que nosso atendimento seja ainda melhor, preciso que você me ajude avaliando como foi o nosso atendimento! https://g.page/PolloMoveis/review?rc";
  3519.                 $messageImagemBody 'entrega-concluida.jpeg';
  3520.                 break;
  3521.                 
  3522.             case 'pedidoImpressoCheckAtSaoJose':
  3523.                 // code...
  3524.                 break;
  3525.                 
  3526.             case 'pedidoPagoCheckAtSaoJose':
  3527.                 // code...
  3528.                 break;
  3529.                 
  3530.             case 'pedidoPagoCheck':
  3531.                 // code...
  3532.                 break;
  3533.                 
  3534.             case 'pedidoRetiradoCheckAtSaoJose':
  3535.                 // code...
  3536.                 break;
  3537.                 
  3538.             case 'pedidoCeletadoCheckAtSaoJose':
  3539.                 // code...
  3540.                 break;
  3541.                 
  3542.             case 'pedidoFotoProdutoCheckAtSaoJose':
  3543.                 // code...
  3544.                 break;
  3545.                 
  3546.             case 'pedidoFotoAssinaturaCheckAtSaoJose':
  3547.                 // code...
  3548.                 break;
  3549.             case 'pedidoMontandoRonald':
  3550.                 // code...
  3551.                 break;
  3552.                 
  3553.             case 'pedidoMontandoFabio':
  3554.                 // code...
  3555.                 break;
  3556.                 
  3557.             case 'pedidoMontandoRian':
  3558.                 // code...
  3559.                 break;
  3560.                 
  3561.             case 'pedidoMontandoMontagemFinalizada':
  3562.                 // code...
  3563.                 break;
  3564.                 
  3565.             case 'aguardandoColeta':
  3566.                 // code...
  3567.                 break;
  3568.                 
  3569.             case 'isColetado':
  3570.                 // code...
  3571.                 break;
  3572.                 
  3573.             case 'pedidoImpressoGuilhermeCheck':
  3574.                 // code...
  3575.                 break;
  3576.                 
  3577.             case 'solicitarMontagem':
  3578.                     $this->createDemandaPedido($pedido'co''montagem'$data->pedido->solicitarMontagem);
  3579.                 break;
  3580.                 
  3581.             case 'solicitarMontagemSaoJose':
  3582.                     $this->createDemandaPedido($pedido'sj''montagem'$data->pedido->solicitarMontagemSaoJose);
  3583.                 break;
  3584.                 
  3585.             case 'solicitarSeparacao':
  3586.                     $this->createDemandaPedido($pedido'co''separacao'$data->pedido->solicitarSeparacao);
  3587.                 break;
  3588.                 
  3589.             case 'solicitarSeparacaoSaoJose':
  3590.                     $this->createDemandaPedido($pedido'sj''separacao'$data->pedido->solicitarSeparacaoSaoJose);
  3591.                 break;
  3592.             
  3593.             default:
  3594.                 return new JsonResponse(['message'=>'Status não localizado'], 400);
  3595.                 break;
  3596.         }
  3597.         
  3598.         if($data->check=='pedidoMontagemCheck' || $data->check=='pedidoEnderecoCheck' || $data->check=='pedidoInstagramCheck' || $data->check=='pedidoGoogleCheck'){
  3599.             
  3600.             $numeroTelefone $pedido->getTelefone();
  3601.             $telefones explode('|'$numeroTelefone);
  3602.             
  3603.             $messageImagemBody 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/' $messageImagemBody '?v='.time();
  3604.             $type 'img';
  3605.             
  3606.             if(count($telefones)>1){
  3607.                 
  3608.                 if($telefones[0]!=$telefones[1]){
  3609.                     
  3610.                     $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  3611.                     $this->sendMensagemViaWhatsapp($type$telefones[1], $messageBody$messageImagemBodynullnull);     
  3612.                     
  3613.                 } else {
  3614.                     $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  3615.                 }
  3616.                 
  3617.             } else {
  3618.                 $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  3619.             }
  3620.             
  3621.         }
  3622.         
  3623.         if($data->check=='solicitarMontagem' || $data->check=='solicitarMontagemSaoJose'){
  3624.             
  3625.             $type "img";
  3626.             
  3627.             $linkChecked = ($data->check=='solicitarMontagemSaoJose') ? 'geovair' 'guilherme';
  3628.             
  3629.             $messageBody "MONTAGEM DOS PRODUTOS.\n\n" "Clique no link para informar que imprimiu e deu andamento na montagem:  https://polo.srvtmp.com.br/app-externo/checked/$linkChecked/$numeroPedido\n\n\nAcesso ao card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  3630.             
  3631.             $img 'https://polo.srvtmp.com.br/montagem.png?v=2';
  3632.             
  3633.             if($data->check=='solicitarMontagem'){ // Coimbra
  3634.             
  3635.                 //$this->sendMensagemViaWhatsapp($type, "5562993126267", $messageBody, $img, null, null); // Guilherme
  3636.                 $this->sendMensagemViaWhatsapp($type"5562993884202"$messageBody$imgnullnull); // Gregory
  3637.                 $this->sendMensagemViaWhatsapp($type"5562994721501"$messageBody$imgnullnull); // Marcos
  3638.                 // $this->sendMensagemViaWhatsapp($type, "5562994542599", $messageBody, $img, null, null); // João Marcos
  3639.             } else { // São José
  3640.             
  3641.                 $this->sendMensagemViaWhatsapp($type"5562993602042"$messageBody$imgnullnull); // Geovair
  3642.                 $this->sendMensagemViaWhatsapp($type"5562981352530"$messageBody$imgnullnull); // Mateus
  3643.                 $this->sendMensagemViaWhatsapp($type"5562995698482"$messageBody$imgnullnull); // Samuel
  3644.                 //$this->sendMensagemViaWhatsapp($type, "5562981854439", $messageBody, $img, null, null); // RIAN 
  3645.                 
  3646.             }
  3647.         }
  3648.         
  3649.         if($data->check=='solicitarSeparacao' || $data->check=='solicitarSeparacaoSaoJose'){
  3650.             
  3651.             $type "img";
  3652.             
  3653.             $linkChecked = ($data->check=='solicitarSeparacaoSaoJose') ? 'geovair' 'guilherme';
  3654.             
  3655.             $messageBody "SEPARAR A MERCADORIA DESMONTADA PARA SER COLETADA OU ENTREGUE.\n\n" "Clique no link para informar que imprimiu e deu andamento na separação:  https://polo.srvtmp.com.br/app-externo/checked/$linkChecked/$numeroPedido\n\n\nAcesso ao card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  3656.             
  3657.             $img 'https://polo.srvtmp.com.br/separacao.png?v=3';
  3658.             
  3659.             if($data->check=='solicitarSeparacao'){ // Coimbra
  3660.             
  3661.                 //$this->sendMensagemViaWhatsapp($type, "5562993126267", $messageBody, $img, null, null); // Guilherme
  3662.                 $this->sendMensagemViaWhatsapp($type"5562994542599"$messageBody$imgnullnull); // João Marcos
  3663.                 $this->sendMensagemViaWhatsapp($type"5562992461439"$messageBody$imgnullnull); // Ronald
  3664.                 // $this->sendMensagemViaWhatsapp($type, "5562999720813", $messageBody, $img, null, null); // Fábio 
  3665.                 // $this->sendMensagemViaWhatsapp($type, "5562994542599", $messageBody, $img, null, null); // João Marcos
  3666.             } else { // São José
  3667.             
  3668.                 $this->sendMensagemViaWhatsapp($type"5562993602042"$messageBody$imgnullnull); // Geovair
  3669.                 $this->sendMensagemViaWhatsapp($type"5562981352530"$messageBody$imgnullnull); // Mateus
  3670.                 $this->sendMensagemViaWhatsapp($type"5562995698482"$messageBody$imgnullnull); // Samuel
  3671.                 
  3672.             }
  3673.         }
  3674.         
  3675.         $this->getDoctrine()->getManager()->flush();
  3676.         
  3677.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  3678.     }
  3679.     
  3680.     private function createDemandaPedido($pedido$local$tipo$acao$clienteVaiBuscarImediatamente=true$isUrgente=true) {
  3681.         
  3682.         $demanda $this->getDoctrine()->getRepository(DemandaPedido::class)->findOneBy([
  3683.             'pedido' => $pedido
  3684.             'local'  => $local,
  3685.             'tipo'   => $tipo
  3686.         ]);
  3687.         
  3688.         if(!$acao && $demanda instanceof DemandaPedido){
  3689.             $this->getDoctrine()->getManager()->remove($demanda);
  3690.             $this->getDoctrine()->getManager()->flush();
  3691.         } else if(!$demanda instanceof DemandaPedido && $acao){
  3692.             
  3693.             $demanda = new DemandaPedido();
  3694.             $demanda->setPedido($pedido);
  3695.             $demanda->setTipo($tipo);
  3696.             $demanda->setLocal($local);
  3697.             $demanda->setStatus('pendente');
  3698.             $demanda->setCreatedAt(new \DateTime());
  3699.             $demanda->setUpdatedAt(new \DateTime());
  3700.             $demanda->setClienteVaiRetirarImediatamente($clienteVaiBuscarImediatamente);
  3701.             $demanda->setIsUrgente($isUrgente);
  3702.             
  3703.             $this->getDoctrine()->getManager()->persist($demanda);
  3704.             $this->getDoctrine()->getManager()->flush();
  3705.             
  3706.         }
  3707.     }
  3708.     
  3709.     /**
  3710.      * @Route("/app-externo/checked/{checkname}/{pedido}", name="checked_pedido", methods={"GET"})
  3711.      */
  3712.     public function checkedPedidoAction(Request $request$checkname$pedido): Response
  3713.     {
  3714.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedido'deletedAt'=>null]);
  3715.         
  3716.         $messageJs 'Pedido não localizado!';
  3717.         
  3718.         if($pedido instanceof EntregaPedido){
  3719.             
  3720.             $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  3721.            
  3722.            if($checkname=='guilherme'){
  3723.                $pedido->setPedidoImpressoGuilhermeCheck(new \DateTime());
  3724.                $this->getDoctrine()->getManager()->flush();
  3725.            } else if($checkname=='geovair') {
  3726.                $pedido->setPedidoPagoCheckAt(new \DateTime());
  3727.                $this->getDoctrine()->getManager()->flush();
  3728.            }
  3729.             
  3730.             $messageJs 'Você enviou uma informação na api e você imprimiu e deu andamento na montagem deste pedido.';
  3731.             exit('<script>alert("'.$messageJs.'");document.location.href="/app-externo#'.$numeroPedido.'";</script>');
  3732.             
  3733.         }
  3734.         
  3735.         exit('<script>alert("'.$messageJs.'");document.location.href="/app-externo";</script>');
  3736.     }
  3737.     
  3738.     private function notificaClienteCriacaoCard($pedido) {
  3739.         
  3740.         $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  3741.         
  3742.         $messageBody "Você comprou na *Pollo Móveis*!\nSeu pedido nº {$pedido->getPedido()} está em preparação.!!\n*Link Pedido:* https://app.moveispollo.com.br/pedido/$numeroPedido";
  3743.         
  3744.         $messageImagemBody 'pedido-recebido.jpeg';
  3745.         $numeroTelefone $pedido->getTelefone();
  3746.         $telefones explode('|'$numeroTelefone);
  3747.         
  3748.         $messageImagemBody 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/' $messageImagemBody '?v='.time();
  3749.         $type 'img';
  3750.         
  3751.         $isRetirada false;
  3752.         
  3753.         if($pedido->getMeioEntrega()=='Retirar no Galpão Coimbra' || $pedido->getMeioEntrega()=='Retirar no Galpão São José' || $pedido->getMeioEntrega()=='Retirar Coimbra/São José'){
  3754.             
  3755.             $isRetirada true;
  3756.             $linkLocalizacao '';
  3757.             $escritaAntes 'Endereço para retirada dos produtos';
  3758.             
  3759.             switch($pedido->getMeioEntrega()) {
  3760.                 
  3761.                 case 'Retirar no Galpão Coimbra':
  3762.                     $linkLocalizacao "*Depósito Coimbra:* Rua 209, 409 - St. Coimbra - Goiânia-Go\nhttps://goo.gl/maps/NFKaVRDiq1eai7jK8";
  3763.                 break;
  3764.                 
  3765.                 case 'Retirar no Galpão São José':
  3766.                     $linkLocalizacao "*Depósito São José:* Av. Dom Eduardo, 881 - St. São José, Goiânia-Go\nhttps://goo.gl/maps/3SLnM32FdSBjk25KA";
  3767.                 break;
  3768.                 
  3769.                 case 'Retirar Coimbra/São José':
  3770.                     $linkLocalizacao "*Depósito Coimbra:* Rua 209, 409 - St. Coimbra - Goiânia-Go\nhttps://goo.gl/maps/NFKaVRDiq1eai7jK8\n\n*Depósito São José:* Av. Dom Eduardo, 881 - St. São José, Goiânia-Go\nhttps://goo.gl/maps/3SLnM32FdSBjk25KA";
  3771.                     $escritaAntes 'Endereço para retirada dos produtos em dois enderecos';
  3772.                 break;
  3773.                 
  3774.                 default:
  3775.                     $linkLocalizacao '';
  3776.                     $isRetirada false;
  3777.                     break;
  3778.             }
  3779.             
  3780.             if($isRetirada){
  3781.                 $messageBody .= "\n\n*$escritaAntes:*\n\n$linkLocalizacao\n\nPix: 12.993.989/0001-60";
  3782.             }
  3783.             
  3784.         }
  3785.         
  3786.         $messageBody_Rastreio "Olá, acompanhe o status da sua entrega clicando no link abaixo\nhttps://app.moveispollo.com.br/acompanhamento/pedido/" $pedido->getCodidoRastreio();
  3787.         $messageImagemBody_Rastreio 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/rastreio_pedido.png?v='.time();;
  3788.         
  3789.         if(count($telefones)>1){
  3790.             
  3791.             if($telefones[0]!=$telefones[1]){
  3792.                 
  3793.                 $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  3794.                 $this->sendMensagemViaWhatsapp($type$telefones[1], $messageBody$messageImagemBodynullnull);  
  3795.                 
  3796.                 if(($pedido->getMeioEntrega()=='Pela Pollo Móveis' || $pedido->getMeioEntrega()=='Viagem pela Pollo Móveis')) {
  3797.                     $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody_Rastreio$messageImagemBody_Rastreionullnull); 
  3798.                     $this->sendMensagemViaWhatsapp($type$telefones[1], $messageBody_Rastreio$messageImagemBody_Rastreionullnull); 
  3799.                 }
  3800.                 
  3801.             } else {
  3802.                 $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);  
  3803.                 
  3804.                 if(($pedido->getMeioEntrega()=='Pela Pollo Móveis' || $pedido->getMeioEntrega()=='Viagem pela Pollo Móveis')) {
  3805.                     $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody_Rastreio$messageImagemBody_Rastreionullnull); 
  3806.                 }
  3807.                 
  3808.             }
  3809.             
  3810.         } else {
  3811.             $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);
  3812.             
  3813.             if(($pedido->getMeioEntrega()=='Pela Pollo Móveis' || $pedido->getMeioEntrega()=='Viagem pela Pollo Móveis')) {
  3814.                 $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody_Rastreio$messageImagemBody_Rastreionullnull);
  3815.             }
  3816.             
  3817.         }
  3818.         
  3819.         $userNotificatonVendedor '';
  3820.         
  3821.         // Envio zap vendedor
  3822.         $usarioVendedor $this->getDoctrine()->getRepository(ContatoBling::class)
  3823.         ->findOneBy(['nome'=>$pedido->getVendedor(), 'grupo'=>'Vendedor']);
  3824.         
  3825.         if($usarioVendedor instanceof ContatoBling){
  3826.             
  3827.             $telefoneItem $usarioVendedor->getTelefone();
  3828.             $contatosSplit explode('|',$telefoneItem);
  3829.             
  3830.             foreach ($contatosSplit as $contatoS){
  3831.                 
  3832.                 $numeroTelefone $this->filterCelular($contatoS);
  3833.                 $numeroTelefone '55' $numeroTelefone;
  3834.                 $this->sendMensagemViaWhatsapp("text"$numeroTelefone$messageBodynullnullnull);
  3835.                 
  3836.             }
  3837.             
  3838.         }
  3839.         
  3840.     }
  3841.     
  3842.     /**
  3843.      * @Route("/app-externo/delete-image", name="delete_image_pedido", methods={"POST"})
  3844.      */
  3845.     public function deleteImagePedido(Request $request): Response
  3846.     {
  3847.         $data json_decode($request->getContent(), false);
  3848.         $user $this->getUser();
  3849.         
  3850.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  3851.         
  3852.         if(!$this->getIsAdmin()) {
  3853.             
  3854.             if($this->getIsEntregador() || $this->getIsEntregadorAux()){
  3855.                 return new JsonResponse($dados400);
  3856.             }
  3857.             
  3858.             if($pedido->getStatus()=='entregue' || $pedido->getStatus()=='baixado' || $pedido->getStatus()=='pendente_admin' ){
  3859.                 return new JsonResponse($dados400);
  3860.             }
  3861.         }
  3862.         if($data->tipo=='nota') {
  3863.             
  3864.             //$pedido->setNotas(null);
  3865.             
  3866.             $fotosNota json_decode($pedido->getNotas(), true);
  3867.             $position 0;
  3868.             if(!isset($fotosNota[0])){
  3869.                 $pedido->setNotas(null);
  3870.             } else {
  3871.                 foreach ($fotosNota as $key=>$fotoNota){
  3872.                     if($fotoNota==$data->foto){
  3873.                         unset($fotosNota[$key]);
  3874.                     }
  3875.                     $position++;
  3876.                 }
  3877.                 
  3878.                 $pedido->setNotas(json_encode($fotosNota));
  3879.             }
  3880.             
  3881.         } else if($data->tipo=='comprovante') {
  3882.             
  3883.             //$pedido->setComprovantePagamento(null);
  3884.             
  3885.             $fotosComprovante json_decode($pedido->getComprovantePagamento(), true);
  3886.             $position 0;
  3887.             if(!isset($fotosComprovante[0])){
  3888.                 $pedido->setComprovantePagamento(null);
  3889.             } else {
  3890.                 foreach ($fotosComprovante as $key=>$fotoComprovante){
  3891.                     if($fotoComprovante==$data->foto){
  3892.                         unset($fotosComprovante[$key]);
  3893.                     }
  3894.                     $position++;
  3895.                 }
  3896.                 
  3897.                 $pedido->setComprovantePagamento(json_encode($fotosComprovante));
  3898.             }
  3899.             
  3900.         } else if($data->tipo=='pedido' || $data->tipo=='pedido_entregue') {
  3901.             
  3902.             $fotosPedidos json_decode($pedido->getFotos(), true);
  3903.             $position 0;
  3904.             if(!isset($fotosPedidos[0])){
  3905.                 $pedido->setFotos(null);
  3906.             } else {
  3907.                 foreach ($fotosPedidos as $key=>$fotoPedido){
  3908.                     if($fotoPedido==$data->foto){
  3909.                         unset($fotosPedidos[$key]);
  3910.                     }
  3911.                     $position++;
  3912.                 }
  3913.                 
  3914.                 $pedido->setFotos(json_encode($fotosPedidos));
  3915.             }
  3916.             
  3917.         } else if($data->tipo=='sinistro') {
  3918.             
  3919.             $fotosPedidos json_decode($pedido->getFotosSinistro(), true);
  3920.             $position 0;
  3921.             if(!isset($fotosPedidos[0])){
  3922.                 $pedido->setFotosSinistro(null);
  3923.             } else {
  3924.                 foreach ($fotosPedidos as $key=>$fotoPedido){
  3925.                     if($fotoPedido==$data->foto){
  3926.                         unset($fotosPedidos[$key]);
  3927.                     }
  3928.                     $position++;
  3929.                 }
  3930.                 $pedido->setFotosSinistro(json_encode($fotosPedidos));
  3931.             }
  3932.         } else if($data->tipo=='assistencia') {
  3933.             
  3934.             $fotosPedidos json_decode($pedido->getFotosAssistencia(), true);
  3935.             $position 0;
  3936.             if(!count($fotosPedidos)){
  3937.                 $pedido->getFotosAssistencia(null);
  3938.             } else {
  3939.                 foreach ($fotosPedidos as $key=>$fotoPedido){
  3940.                     if($fotoPedido==$data->foto){
  3941.                         unset($fotosPedidos[$key]);
  3942.                     }
  3943.                     $position++;
  3944.                 }
  3945.                 $pedido->setFotosAssistencia(json_encode($fotosPedidos));
  3946.             }
  3947.         }
  3948.         
  3949.         $this->getDoctrine()->getManager()->flush();
  3950.         $fotos json_decode($pedido->getFotos());
  3951.         $fotosSinistro json_decode($pedido->getFotosSinistro());
  3952.         $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  3953.         $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  3954.         $fotosNotas json_decode($pedido->getNotas());
  3955.         
  3956.         return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia], $this->todosPedidosPorStatus()), 200);
  3957.     }
  3958.     
  3959.     /**
  3960.      * @Route("/app-externo/busca-pedido", name="busca_pedido", methods={"GET"})
  3961.      */
  3962.     public function buscaPedidoBling(Request $request,  HttpClientInterface $client): Response
  3963.     {
  3964.         if($request->get('tipo')=='pedido' || $request->get('tipo')=='pedido_entregue') {
  3965.             
  3966.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$request->get('pedido'), 'deletedAt'=>null]);
  3967.             if($pedido instanceof EntregaPedido){
  3968.                 return new JsonResponse(['message'=>"Este pedido já está cadastrado no sistema."], 400);
  3969.             }
  3970.             
  3971.         } else {
  3972.             
  3973.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$request->get('pedido'), 'deletedAt'=>null]);
  3974.             if($pedido instanceof EntregaPedido){
  3975.                 return new JsonResponse(['message'=>"Este pedido já está cadastrado no sistema."], 400);
  3976.             }
  3977.             
  3978.         }
  3979.         
  3980.         $dados = [];
  3981.         
  3982.         if($request->get('tipo')=='pedido' || $request->get('tipo')=='pedido_entregue') {
  3983.             $dados $this->getPedido(trim($request->get('pedido')), $client$request->get('tipo'));
  3984.         } else {
  3985.             $dados $this->getNotaFiscal(trim($request->get('pedido')), $client$request->get('tipo'));
  3986.         }
  3987.         
  3988.         return new JsonResponse($dados200);
  3989.     }
  3990.     
  3991.     /**
  3992.      * @Route("/app-externo/busca-pedido-customizado-detalhe", name="busca_pedido_customizado_detalhe", methods={"GET"})
  3993.      */
  3994.     public function buscaPedidoCustomizadoDetalheBling(Request $request,  HttpClientInterface $client): Response
  3995.     {
  3996.         $pedidoLocal $this->getDoctrine()->getRepository(EntregaPedido::class)
  3997.         ->findOneBy(['pedido'=>$request->get('p'), 'deletedAt'=>NULL]);
  3998.         
  3999.         $pedidoReplace str_replace('-Assistência',''$request->get('p'));
  4000.         if(!$pedidoLocal instanceof EntregaPedido || $request->get('nf')=='s') {
  4001.             
  4002.             $linkNf $this->getNotaFiscalLink($pedidoReplace$client);
  4003.             
  4004.             if($linkNf!=''){
  4005.                 header("Location: " $linkNf);
  4006.                 exit;
  4007.             }
  4008.             exit('Este link não corresponde à uma NF e nem pedido.');
  4009.         }
  4010.         
  4011.         $dados $this->getPedido(trim($pedidoReplace), $clienttrue$pedidoLocal);
  4012.                 
  4013.         $endereco nl2br($pedidoLocal->getEnderecoSocialCustomizado());
  4014.         
  4015.         $totalDeProdutos 0;
  4016.         $itens json_decode($pedidoLocal->getItensPedidoCustomizado());
  4017.         
  4018.         foreach ($itens as $item) {
  4019.             $totalDeProdutos += $item->valorTotal;
  4020.         }
  4021.         
  4022.         $valor_com_desconto $totalDeProdutos;
  4023.         if($pedidoLocal->getDesconto() > 0){
  4024.             //$valor_com_desconto = $totalDeProdutos - ($totalDeProdutos * ($pedidoLocal->getDesconto() / 100));
  4025.             $valor_com_desconto $totalDeProdutos $pedidoLocal->getDesconto();
  4026.             $valor_com_desconto round($valor_com_desconto2);
  4027.         }
  4028.         
  4029.         //$valor_com_frete = $totalDeProdutos+$pedidoLocal->getFreteCustomizado();
  4030.         
  4031.         $valor_com_desconto $valor_com_desconto+$pedidoLocal->getFreteCustomizado();
  4032.         return $this->render('app_externo/telas/pedido-customizado.html.twig', [
  4033.             'dados'=> $dados'com_obs'=>true,
  4034.             'razaoSocial'=> $pedidoLocal->getRazaoSocialCustomizado(), 
  4035.             'cliente'=> $pedidoLocal->getClienteCustomizado(),
  4036.             'formaPagamento'=> $pedidoLocal->getFormaPagamentoCustomizado(),
  4037.             'itens'=> $itens,
  4038.             'frete'=> number_format($pedidoLocal->getFreteCustomizado(), 2',''.'), 
  4039.             'endereco'=> $endereco,
  4040.             'totalDeProdutos'=> number_format($valor_com_desconto2',''.'),
  4041.             'valorTotalComDesconto' => number_format($valor_com_desconto2',''.'),
  4042.             'vendedorCustomizado' => $pedidoLocal->getVendedorCustomizado(),
  4043.             'desconto' => number_format($pedidoLocal->getDesconto(), 2',''.')
  4044.         ]);
  4045.     }
  4046.     
  4047.     /**
  4048.      * @Route("/app-externo/busca-pedido-detalhe", name="busca_pedido_detalhe", methods={"GET"})
  4049.      */
  4050.     public function buscaPedidoDetalheBling(Request $request,  HttpClientInterface $client): Response
  4051.     {
  4052.         $pedidoLocal $this->getDoctrine()->getRepository(EntregaPedido::class)
  4053.         ->findOneBy(['pedido'=>$request->get('p'), 'deletedAt'=>NULL]);
  4054.         
  4055.         $pedidoReplace str_replace('-Assistência',''$request->get('p'));
  4056.         if(!$pedidoLocal instanceof EntregaPedido || $request->get('nf')=='s') {
  4057.             
  4058.             $linkNf $this->getNotaFiscalLink($pedidoReplace$client);
  4059.             
  4060.             if($linkNf!=''){
  4061.                 header("Location: " $linkNf);
  4062.                 exit;
  4063.             }
  4064.             exit('Este link não corresponde à uma NF e nem pedido.');
  4065.         }
  4066.         
  4067.         $dados $this->getPedido(trim($pedidoReplace), $clienttrue$pedidoLocal);
  4068.         if($dados['endereco_entrega']==''){
  4069.             $dados['endereco_entrega'] = $pedidoLocal->getNovoEnderecoEntrega();
  4070.         }
  4071.         
  4072.         $assinaturaAceitePedido '';
  4073.         $assinadoAt '';
  4074.         $demanda $this->getDoctrine()->getRepository(DemandaPedido::class)->findOneBy(['pedido'=>$pedidoLocal]);
  4075.         if($demanda instanceof DemandaPedido){
  4076.             if($demanda->getAssinatura()!=null){
  4077.                 $assinaturaAceitePedido $demanda->getAssinatura();
  4078.                 $assinadoAt = [
  4079.                     'dia' => $demanda->getAssinadoAt()->format('d'),
  4080.                     'mes' => $demanda->getAssinadoAt()->format('m'),
  4081.                     'ano' => $demanda->getAssinadoAt()->format('Y')
  4082.                 ];
  4083.             }
  4084.         }
  4085.             
  4086.         return $this->render('app_externo/telas/pedido.html.twig', ['dados'=>$dados'com_obs'=>true'assinatura'=>$assinaturaAceitePedido'assinadoAt'=>$assinadoAt]);
  4087.     }
  4088.     
  4089.     private function getNotaFiscalLink($numero$client) {
  4090.         
  4091.         $linkNf '';
  4092.         
  4093.         $response $client->request(
  4094.             'GET',
  4095.             SincronizacaoController::URL_API_BLING '/notafiscal/'.$numero.'/1/json/',
  4096.             [
  4097.                 'query' => [
  4098.                     'apikey' => SincronizacaoController::KEY_API_POLLO
  4099.                 ]
  4100.             ]
  4101.         );
  4102.         $statusCode $response->getStatusCode();
  4103.         if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
  4104.             $content $response->toArray();
  4105.             if(isset($content['retorno'])){
  4106.                 if(isset($content['retorno']['notasfiscais'])){
  4107.                     if(count($content['retorno']['notasfiscais']) > 0) {
  4108.                         $notafiscal $content['retorno']['notasfiscais'][0]['notafiscal'];
  4109.                         $linkNf str_ireplace("\\",""$notafiscal['linkDanfe']);
  4110.                     }
  4111.                 }
  4112.             }
  4113.         }
  4114.         
  4115.         return $linkNf;
  4116.     }
  4117.     
  4118.     /**
  4119.      * @Route("/app-externo/get-pedidos-publico/{pedido}", name="get_pedidos_publico", methods={"GET"})
  4120.      */
  4121.     public function getPedidosPublico(Request $request$pedido): Response
  4122.     {
  4123.         $pedidosLocalizados = [];
  4124.         $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoPorNotaOuPedido($pedido);
  4125.         
  4126.         foreach ($pedidos as $pedido){
  4127.             
  4128.             $pedidoNumero = empty($pedido->getPedido()) ? $pedido->getNotaFiscal() . '-NF' $pedido->getPedido();
  4129.             $pedidosLocalizados[] = [
  4130.                 'id' => $pedido->getId(),
  4131.                 'titulo' => $pedidoNumero
  4132.             ];
  4133.             
  4134.         }
  4135.         
  4136.         return new JsonResponse($pedidosLocalizados200);
  4137.     }
  4138.     
  4139.     /**
  4140.      * @Route("/app-externo/get-images-pedido", name="get_images_pedido", methods={"GET"})
  4141.      */
  4142.     public function getImagesPedido(Request $request): Response
  4143.     {
  4144.         $fotos = [];
  4145.         $acessoPublico false;
  4146.         
  4147.         if(!$this->getUser() instanceof User){
  4148.             $acessoPublico true;
  4149.         }
  4150.         
  4151.         if($request->get('num_pedido')){
  4152.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$request->get('num_pedido'), 'deletedAt'=>null]);
  4153.             if(!$pedido instanceof EntregaPedido){
  4154.                 return new JsonResponse(['fotos'=>$fotos], 400);
  4155.             }
  4156.         } else {
  4157.             $idPedido $request->get('id');
  4158.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4159.         }
  4160.         if(!$pedido instanceof EntregaPedido){
  4161.             return new JsonResponse(['fotos'=>$fotos], 200);
  4162.         }
  4163.         
  4164.         $fotos json_decode($pedido->getFotos());
  4165.         $fotosSinistro json_decode($pedido->getFotosSinistro());
  4166.         $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  4167.         $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  4168.         $fotosNotas json_decode($pedido->getNotas());
  4169.         
  4170.         // Pega a demanda
  4171.         $temAssinatura false;
  4172.         $demanda $this->getDoctrine()->getRepository(DemandaPedido::class)->findOneBy(['pedido'=>$pedido]);
  4173.         if($demanda instanceof DemandaPedido){
  4174.             if($demanda->getAssinatura()!=null){
  4175.                 $fotosNotas[] = $demanda->getAssinatura();
  4176.                 $temAssinatura true;
  4177.             }
  4178.         }
  4179.         
  4180.         $motorista '';
  4181.         if($pedido->getColaboradorUser() instanceof User){
  4182.             $motorista strtoupper($pedido->getColaboradorUser()->getEmail());
  4183.         }
  4184.         
  4185.         $statusConcluido '';
  4186.         
  4187.         if($pedido->getStatus()=='entregue'){
  4188.             $statusConcluido 'Concluído';
  4189.         }
  4190.         
  4191.         $iniciouEntrega false;
  4192.         
  4193.         if($pedido->getStatus()=='transito'){
  4194.             $iniciouEntrega true;
  4195.         }
  4196.         
  4197.         if($acessoPublico) {
  4198.             
  4199.             $localizacao = ($pedido->getLocalizacao()=='' || $pedido->getLocalizacao()==null) ? $pedido->getLinkEnderecoEntrega() : '';
  4200.             
  4201.             return new JsonResponse(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia'temAssinatura'=>$temAssinatura'pedidoContato'=>$this->abreviarNome($pedido->getContato()), 'codigoCurrentPedido'=>$pedido->getPedido(), 'idPedido'=>$pedido->getId(), 'auxiliar' => strtoupper($pedido->getAuxiliar()), 'motorista' => $motorista'concluido'=>$statusConcluido'inicioEntrega'=>$iniciouEntrega'observacaoCadastro'=>$pedido->getObservacaoCadastro(), 'endereco_entrega'=>$pedido->getEnderecoEntrega(), 'localizacao'=>$localizacao], 200);
  4202.         }
  4203.         
  4204.         return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia'temAssinatura'=>$temAssinatura'pedidoContato'=>$this->abreviarNome($pedido->getContato()), 'codigoCurrentPedido'=>$pedido->getPedido(), 'idPedido'=>$pedido->getId(), 'auxiliar' => strtoupper($pedido->getAuxiliar()), 'motorista' => $motorista'concluido'=>$statusConcluido], $this->todosPedidosPorStatus()), 200);
  4205.     }
  4206.     
  4207.     private function abreviarNome($nomeCompleto) {
  4208.         // Separa o nome completo em partes
  4209.         $partes explode(' '$nomeCompleto);
  4210.     
  4211.         // Se houver apenas um nome, retorna como está
  4212.         if (count($partes) == 1) {
  4213.             return $nomeCompleto;
  4214.         }
  4215.     
  4216.         // Mantém o primeiro e o último nome completos
  4217.         $primeiroNome array_shift($partes);
  4218.         $ultimoNome array_pop($partes);
  4219.     
  4220.         // Converte os nomes intermediários para iniciais
  4221.         $iniciais '';
  4222.         foreach ($partes as $parte) {
  4223.             $iniciais .= strtoupper($parte[0]) . '. ';
  4224.         }
  4225.     
  4226.         // Concatena o primeiro nome, as iniciais e o último nome
  4227.         return $primeiroNome ' ' $iniciais $ultimoNome;
  4228.     }
  4229.     
  4230.     /**
  4231.      * @Route("/app-externo/uplod-image-pedido-assistencia", name="upload_image_pedido_assistencia", methods={"POST"})
  4232.      */
  4233.     public function uploadImagePedidoAssistencia(Request $request): Response
  4234.     {
  4235.         $data json_decode($request->getContent(), false);
  4236.         $idPedido $request->get('id');
  4237.         //$ext = explode('.',$_FILES['file']['name']);
  4238.         $imageName rand(100000999999) . time();
  4239.         $filename "$imageName.jpeg";
  4240.         $uploadfile '/www/wwwroot/gestor.moveispollo.com.br/public/img_assistencia/'.$filename;
  4241.         
  4242.         $img str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
  4243.         $img str_replace(' ''+'$img);
  4244.         $data base64_decode($img);
  4245.         file_put_contents($uploadfile$data);
  4246.             
  4247.         //if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
  4248.             
  4249.             $fotos = [];
  4250.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4251.             if($pedido->getFotosAssistencia()!='' && $pedido->getFotosAssistencia() !=null){
  4252.                 $fotos json_decode($pedido->getFotosAssistencia());
  4253.             }
  4254.             
  4255.             $fotos[] = $filename;
  4256.             $pedido->setFotosAssistencia(json_encode($fotos));
  4257.             $this->getDoctrine()->getManager()->flush();
  4258.             
  4259.             $fotos json_decode($pedido->getFotos());
  4260.             $fotosSinistro json_decode($pedido->getFotosSinistro());
  4261.             $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  4262.             $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  4263.             $fotosNotas json_decode($pedido->getNotas());
  4264.             
  4265.             return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia],$this->todosPedidosPorStatus()), 200);
  4266.         //}
  4267.         
  4268.         //return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante'=>'', 'assistencia'=>[]],$this->todosPedidosPorStatus()), 400);
  4269.     }
  4270.     
  4271.     /**
  4272.      * @Route("/app-externo/uplod-image-pedido-sinitro", name="upload_image_pedido_sinistro", methods={"POST"})
  4273.      */
  4274.     public function uploadImagePedidoSinistro(Request $request): Response
  4275.     {
  4276.         $data json_decode($request->getContent(), false);
  4277.         $idPedido $request->get('id');
  4278.         //$ext = explode('.',$_FILES['file']['name']);
  4279.         $imageName rand(100000999999) . time();
  4280.         $filename "$imageName.jpeg";
  4281.         $uploadfile '/www/wwwroot/gestor.moveispollo.com.br/public/img_sinistro/'.$filename;
  4282.         
  4283.         $img str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
  4284.         $img str_replace(' ''+'$img);
  4285.         $data base64_decode($img);
  4286.         file_put_contents($uploadfile$data);
  4287.             
  4288.         //if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
  4289.             
  4290.             $fotos = [];
  4291.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4292.             if($pedido->getFotosSinistro()!='' && $pedido->getFotosSinistro() !=null){
  4293.                 $fotos json_decode($pedido->getFotosSinistro());
  4294.             }
  4295.             
  4296.             $fotos[] = $filename;
  4297.             $pedido->setFotosSinistro(json_encode($fotos));
  4298.             $this->getDoctrine()->getManager()->flush();
  4299.             
  4300.             $fotos json_decode($pedido->getFotos());
  4301.             $fotosSinistro json_decode($pedido->getFotosSinistro());
  4302.             $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  4303.             $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  4304.             $fotosNotas json_decode($pedido->getNotas());
  4305.             
  4306.             return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia], $this->todosPedidosPorStatus()), 200);
  4307.         //}
  4308.         
  4309.         //return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante'=>'', 'assistencia'=>[]],$this->todosPedidosPorStatus()), 400);
  4310.     }
  4311.     
  4312.     /**
  4313.      * @Route("/app-externo/uplod-image-comprovante", name="upload_image_comprovante", methods={"POST"})
  4314.      */
  4315.     public function uploadImageComprovante(Request $request): Response
  4316.     {
  4317.         $data json_decode($request->getContent(), false);
  4318.         $idPedido $request->get('id');
  4319.         //$ext = explode('.',$_FILES['file']['name']);
  4320.         $imageName rand(100000999999) . time();
  4321.         $filename "$imageName.jpeg";
  4322.         $uploadfile '/www/wwwroot/gestor.moveispollo.com.br/public/img_comprovante_pagamento/'.$filename;
  4323.         
  4324.         $img str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
  4325.         $img str_replace(' ''+'$img);
  4326.         $data base64_decode($img);
  4327.         file_put_contents($uploadfile$data);
  4328.             
  4329.         //if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
  4330.         
  4331.             $fotos = [];
  4332.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4333.             if($pedido->getComprovantePagamento()!='' && $pedido->getComprovantePagamento() !=null){
  4334.                 $fotos json_decode($pedido->getComprovantePagamento());
  4335.             }
  4336.             $fotos[] = $filename;
  4337.             
  4338.             $pedido->setComprovantePagamento(json_encode($fotos));
  4339.             $this->getDoctrine()->getManager()->flush();
  4340.             
  4341.             $fotosSinistro json_decode($pedido->getFotosSinistro());
  4342.             $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  4343.             $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  4344.             $fotosNotas json_decode($pedido->getNotas());
  4345.             
  4346.             $todosPedios = [];
  4347.             if($this->getUser() instanceof User){
  4348.                 $todosPedios $this->todosPedidosPorStatus();
  4349.             }
  4350.             
  4351.             return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia], $todosPedios), 200);
  4352.             
  4353.             #### ANTIGA
  4354.             
  4355.             // $pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4356.             // $pedido->setComprovantePagamento($filename);
  4357.             // $this->getDoctrine()->getManager()->flush();
  4358.             // $fotos = json_decode($pedido->getFotos());
  4359.             
  4360.             // $fotosSinistro = json_decode($pedido->getFotosSinistro());
  4361.             // $fotosAssistencia = json_decode($pedido->getFotosAssistencia());
  4362.             
  4363.             // return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$pedido->getNotas(), 'sinistros'=>$fotosSinistro, 'comprovante'=>$pedido->getComprovantePagamento(), 'fotos_assistencia'=>$fotosAssistencia], $this->todosPedidosPorStatus()), 200);
  4364.             
  4365.             #### ANTIGA
  4366.             
  4367.         //}
  4368.         
  4369.         
  4370.         //return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante' =>'', 'assistencia'=>[]], $this->todosPedidosPorStatus()), 400);
  4371.     }
  4372.     
  4373.     /**
  4374.      * @Route("/app-externo/uplod-image-pedido", name="upload_image_pedido", methods={"POST"})
  4375.      */
  4376.     public function uploadImagePedido(Request $request): Response
  4377.     {
  4378.         $data json_decode($request->getContent(), false);
  4379.         $idPedido $request->get('id');
  4380.         //$ext = explode('.',$_FILES['file']['name']);
  4381.         $imageName rand(100000999999) . time();
  4382.         $filename "$imageName.jpeg";
  4383.         $uploadfile '/www/wwwroot/gestor.moveispollo.com.br/public/img_pedidos/'.$filename;
  4384.         
  4385.         $img str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
  4386.         $img str_replace(' ''+'$img);
  4387.         $data base64_decode($img);
  4388.         file_put_contents($uploadfile$data);
  4389.         //if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
  4390.             
  4391.             $fotos = [];
  4392.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4393.             if($pedido->getFotos()!='' && $pedido->getFotos() !=null){
  4394.                 $fotos json_decode($pedido->getFotos());
  4395.             }
  4396.             
  4397.             $fotos[] = $filename;
  4398.             $pedido->setFotos(json_encode($fotos));
  4399.             $this->getDoctrine()->getManager()->flush();
  4400.             
  4401.             $fotos json_decode($pedido->getFotos());
  4402.             $fotosSinistro json_decode($pedido->getFotosSinistro());
  4403.             $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  4404.             $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  4405.             $fotosNotas json_decode($pedido->getNotas());
  4406.             
  4407.             $todosPedios = [];
  4408.             if($this->getUser() instanceof User){
  4409.                 $todosPedios $this->todosPedidosPorStatus();
  4410.             }
  4411.             
  4412.             return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia], $todosPedios), 200);
  4413.         //}
  4414.         
  4415.         //return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante' =>'', 'assistencia'=>[]], $this->todosPedidosPorStatus()), 400);
  4416.     }
  4417.     
  4418.     /**
  4419.      * @Route("/app-externo/uplod-image-nota", name="upload_image_nota", methods={"POST"})
  4420.      */
  4421.     public function uploadImageNota(Request $request): Response
  4422.     {
  4423.         $data json_decode($request->getContent(), false);
  4424.         $idPedido $request->get('id');
  4425.         //$ext = explode('.',$_FILES['file']['name']);
  4426.         $imageName rand(100000999999) . time();
  4427.         $filename "$imageName.jpeg";
  4428.         $uploadfile '/www/wwwroot/gestor.moveispollo.com.br/public/img_notas/'.$filename;
  4429.         
  4430.         $img str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
  4431.         $img str_replace(' ''+'$img);
  4432.         $data base64_decode($img);
  4433.         file_put_contents($uploadfile$data);
  4434.             
  4435.         //if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
  4436.         
  4437.             $fotos = [];
  4438.             $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4439.             if($pedido->getNotas()!='' && $pedido->getNotas() !=null){
  4440.                 $fotos json_decode($pedido->getNotas());
  4441.             }
  4442.             $fotos[] = $filename;
  4443.             
  4444.             $pedido->setNotas(json_encode($fotos));
  4445.             $this->getDoctrine()->getManager()->flush();
  4446.             
  4447.             $fotosSinistro json_decode($pedido->getFotosSinistro());
  4448.             $fotosAssistencia json_decode($pedido->getFotosAssistencia());
  4449.             $fotosComprovantes json_decode($pedido->getComprovantePagamento());
  4450.             $fotosNotas json_decode($pedido->getNotas());
  4451.             
  4452.             // $pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
  4453.             // $pedido->setNotas($filename);
  4454.             // $this->getDoctrine()->getManager()->flush();
  4455.             // $fotos = json_decode($pedido->getFotos());
  4456.             
  4457.             // $fotosSinistro = json_decode($pedido->getFotosSinistro());
  4458.             // $fotosAssistencia = json_decode($pedido->getFotosAssistencia());
  4459.             // $fotosComprovantes = json_decode($pedido->getComprovantePagamento());
  4460.             
  4461.                         
  4462.             $todosPedios = [];
  4463.             if($this->getUser() instanceof User){
  4464.                 $todosPedios $this->todosPedidosPorStatus();
  4465.             }
  4466.             
  4467.             return new JsonResponse(array_merge(['fotos'=>$fotos'notas'=>$fotosNotas'sinistros'=>$fotosSinistro'comprovante'=>$fotosComprovantes'fotos_assistencia'=>$fotosAssistencia], $todosPedios), 200);
  4468.         //}
  4469.         
  4470.         //return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante' =>'', 'assistencia'=>[]], $this->todosPedidosPorStatus()), 400);
  4471.     }
  4472.     
  4473.     /**
  4474.      * @Route("/app-externo/muda_status_novos_pedidos", name="muda_status_novos_pedidos", methods={"POST"})
  4475.      */
  4476.     public function muda_status_novos_pedidos(Request $request): Response
  4477.     {
  4478.         $data json_decode($request->getContent(), false);
  4479.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  4480.         
  4481.         if(!$pedido instanceof EntregaPedido){
  4482.             return new JsonResponse($pedidosData400);
  4483.         }
  4484.                 
  4485.         
  4486.         if($data->tipo=='pago'){
  4487.             $pedido->setIsPagoGeralAt(new \DateTime());
  4488.         } else {
  4489.             $pedido->setIsEntregueGeralAt(new \DateTime());
  4490.         }
  4491.         
  4492.         $this->getDoctrine()->getManager()->flush();
  4493.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  4494.     }
  4495.     
  4496.     /**
  4497.      * @Route("/app-externo/edita-entrega", name="edita_entrega", methods={"POST"})
  4498.      */
  4499.     public function editaEntrega(Request $request): Response
  4500.     {
  4501.         $data json_decode($request->getContent(), false);
  4502.         $pedidoLocalizado false;
  4503.         
  4504.         $esperarClientePagar 'Não';
  4505.         
  4506.         if(isset($data->esperarClientePagar)){
  4507.             $esperarClientePagar $data->esperarClientePagar;
  4508.         }
  4509.         
  4510.         $entregaNova $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
  4511.         
  4512.         // if($data->nota!='') {
  4513.         //     $pedidoId = intval($data->nota);
  4514.         //     $entregaNova = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$pedidoId, 'deletedAt'=>null]);
  4515.         // } else {
  4516.         //     $pedidoId = intval($data->pedido);
  4517.         //     $entregaNova = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoId, 'deletedAt'=>null]);
  4518.         // }
  4519.         
  4520.         if(!$entregaNova instanceof EntregaPedido) {
  4521.             return new JsonResponse(['message'=>'Este pedido não existe no sistema.'], 400);
  4522.         }
  4523.         
  4524.         // validações somente para cadastro de vendedor
  4525.         if($this->getIsVendedor()) {
  4526.             if(
  4527.                 ($data->assistencia=='Sim' && $data->periodosEntrega=='' && $data->meioEntrega==''/* Validações assistencia */
  4528.                 ||
  4529.                 ($data->assistencia=='Não' && $data->periodosEntrega=='' && $data->meioEntrega=='' && 
  4530.                 $data->formaPagamento=='' && $data->periodosEntrega==''/* Validações não assistencia */
  4531.             ) {
  4532.                 return new JsonResponse(['message'=>'Todos os campos do formulário são obrigatórios para o cadastro do pedido.'], 400);
  4533.             }
  4534.         }
  4535.         
  4536.         $user $this->getUser();
  4537.         $entregaNova->setUpdatedAt(new \DateTime('now'));
  4538.         
  4539.         $urgente false;
  4540.         if(isset($data->isUrgente)) {
  4541.             $urgente = ($data->isUrgente=='Sim') ? true false;
  4542.         }
  4543.         
  4544.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4545.             if(isset($data->montagem)) {
  4546.                $entregaNova->setMontagem($data->montagem);
  4547.             }
  4548.         }
  4549.         
  4550.         if(isset($data->separarMontarPedido)) {
  4551.             $entregaNova->setSepararMontarPedido($data->separarMontarPedido);
  4552.         }
  4553.         
  4554.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4555.             if(isset($data->assistencia)) {
  4556.                 $entregaNova->setAssistencia($data->assistencia);
  4557.             }
  4558.         }
  4559.         
  4560.         // if(isset($data->tipoDocumento)) {
  4561.         //     $entregaNova->setTipoDocumento($data->tipoDocumento);
  4562.         // }
  4563.         
  4564.         if(isset($data->formaPagamento)) {
  4565.             $entregaNova->setFormaPagamento($data->formaPagamento);
  4566.         }
  4567.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4568.             if(isset($data->periodosEntrega)) {
  4569.                 
  4570.                 $entregaNova->setPeriodoEntrega($data->periodosEntrega);
  4571.                 
  4572.                 if(isset($data->horarioEntrega)) {
  4573.                     
  4574.                     if($data->horarioEntrega!="Não informado"){
  4575.                         $horario = \DateTime::createFromFormat('H:i'$data->horarioEntrega);
  4576.                         $entregaNova->setHorarioEntrega($horario);
  4577.                     }
  4578.                     
  4579.                 }
  4580.                 
  4581.             }
  4582.         }
  4583.         
  4584.         if(isset($data->meioEntrega)) {
  4585.             $entregaNova->setMeioEntrega($data->meioEntrega);
  4586.         }
  4587.         
  4588.         if(isset($data->montarMoveis)) {
  4589.             $entregaNova->setMontarMoveis($data->montarMoveis);
  4590.         }
  4591.         
  4592.         $entregaNova->setIsUrgente($urgente);
  4593.         
  4594.         if(isset($data->observacaoCadastro)){
  4595.             $entregaNova->setObservacaoCadastro($data->observacaoCadastro);
  4596.         }
  4597.         
  4598.         if(isset($data->endereco)){
  4599.             $entregaNova->setEndereco($data->endereco);
  4600.             if($data->endereco!=''){
  4601.                 $enderecoEntregaParaGeocode $data->endereco;
  4602.             }
  4603.         }
  4604.         
  4605.         if(isset($data->logradouro)){
  4606.             
  4607.             if($data->logradouro!=''){
  4608.                 
  4609.                 $endereco $data->logradouro;
  4610.             
  4611.                 if(isset($data->enderecoComplemento)){
  4612.                     if($data->enderecoComplemento!=''){
  4613.                         $endereco .= ', ' $data->enderecoComplemento ',  CEP: ' $data->cepBusca;
  4614.                     }
  4615.                 }
  4616.                 $entregaNova->setNovoEnderecoEntrega($endereco);
  4617.                 $enderecoEntregaParaGeocode $endereco;
  4618.                 
  4619.             }
  4620.             // $entregaNova->setNovoEnderecoEntrega($data->novoEnderecoEntrega);
  4621.             // if($data->novoEnderecoEntrega!=''){
  4622.             //     $enderecoEntregaParaGeocode = $data->novoEnderecoEntrega;
  4623.             // }
  4624.             
  4625.         }
  4626.         
  4627.         
  4628.         if(isset($data->enderecoPadraoGoogle)){
  4629.             
  4630.             if($data->enderecoPadraoGoogle!=''){
  4631.                 $entregaNova->setNovoEnderecoEntrega($data->enderecoPadraoGoogle);
  4632.                 $enderecoEntregaParaGeocode $data->enderecoPadraoGoogle;
  4633.             }
  4634.             
  4635.         }
  4636.         
  4637.         if(isset($data->pontoReferencia)){
  4638.             
  4639.             if($data->pontoReferencia!=''){
  4640.                 $entregaNova->setEnderecoPontoReferencia($data->pontoReferencia);
  4641.             }
  4642.             
  4643.         }
  4644.         
  4645.         $entregaNova->setContato($data->contato);
  4646.         
  4647.         if(isset($data->tipoFrete)){
  4648.             $entregaNova->setTipoFrete($data->tipoFrete);
  4649.         }
  4650.         
  4651.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4652.             if(isset($data->embalagem)){
  4653.                 $entregaNova->setEmbalagem($data->embalagem);
  4654.             }
  4655.         }
  4656.         
  4657.         if(!$pedidoLocalizado){
  4658.             $this->getDoctrine()->getManager()->persist($entregaNova); 
  4659.         }
  4660.         
  4661.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4662.             if(isset($data->estaPago)){
  4663.                 $entregaNova->setEstaPago($data->estaPago);
  4664.             } else {
  4665.                 $entregaNova->setEstaPago("Não");
  4666.             }
  4667.         }
  4668.         
  4669.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4670.             if(isset($data->receberNaEntrega)){
  4671.                 $entregaNova->setReceberNaEntrega($data->receberNaEntrega);
  4672.             } else {
  4673.                 $entregaNova->setReceberNaEntrega("Não");
  4674.             }
  4675.         }
  4676.         
  4677.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4678.             if(isset($data->despacharTrocar)){
  4679.                 $entregaNova->setDespacharTrocar($data->despacharTrocar);
  4680.             }
  4681.         }
  4682.         
  4683.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4684.             if(isset($data->ladoMontagemBalcao) && $data->ladoMontagemBalcao!=''){
  4685.                 $entregaNova->setLadoMontagemBalcao($data->ladoMontagemBalcao);
  4686.             }
  4687.         }
  4688.         
  4689.         if(isset($data->tipoDocumento)) {
  4690.             $entregaNova->setTipoDocumento($data->tipoDocumento);
  4691.         }
  4692.         
  4693.         if(isset($data->estaPagoLoja)) {
  4694.             $entregaNova->setPagoNaLoja($data->estaPagoLoja);
  4695.         }
  4696.         
  4697.         if(isset($data->cnpj)) {
  4698.             $entregaNova->setCnpj($data->cnpj);
  4699.         }
  4700.         
  4701.         if(isset($data->linkEnderecoEntrega)){
  4702.             $entregaNova->setLinkEnderecoEntrega($data->linkEnderecoEntrega);
  4703.         }
  4704.         
  4705.         if($this->getIsVendedor() || $this->getIsAdmin()) {
  4706.             if(isset($data->entregarHoje)) {
  4707.                 
  4708.                 $entregaNova->setEntregarHoje($data->entregarHoje);
  4709.                 
  4710.                 if($data->entregarHoje=='Agendar') {
  4711.                     
  4712.                     if(isset($data->dataEntrega)) {
  4713.                         $dataEntrega = \DateTime::createFromFormat('Y-m-d'$data->dataEntrega);
  4714.                         $dataEntrega->setTime(235959);
  4715.                         if($dataEntrega instanceof \DateTime) {
  4716.                             $entregaNova->setDataEntrega($dataEntrega);
  4717.                         }
  4718.                     }
  4719.     
  4720.                 }
  4721.             }
  4722.         }
  4723.         
  4724.         if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis') && $esperarClientePagar=='Não') {
  4725.             if(isset($data->dataEntrega)) {
  4726.                 $dataEntrega = \DateTime::createFromFormat('d/m/Y'$data->dataEntrega);
  4727.                 $dataEntrega->setTime(235959);
  4728.                 if($dataEntrega instanceof \DateTime) {
  4729.                     $entregaNova->setDataEntrega($dataEntrega);
  4730.                 }
  4731.             }
  4732.             
  4733.         }
  4734.         
  4735.         if(isset($data->linkShare)) {
  4736.             $entregaNova->setLinkShare($data->linkShare);
  4737.         }
  4738.         
  4739.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4740.             
  4741.             if(isset($data->desejaEnviarZapSeparador)){
  4742.                 
  4743.                 if(isset($data->meioEntrega) && isset($data->desejaEnviarZapSeparador)){
  4744.                     
  4745.                     $entregaNova->setDesejaEnviarZapSeparador($data->desejaEnviarZapSeparador);
  4746.                 }
  4747.             }
  4748.             
  4749.         }
  4750.         
  4751.         if(isset($data->solicitarColeta)) {
  4752.             $entregaNova->setSolicitarColeta($data->solicitarColeta);
  4753.         }
  4754.         
  4755.         if(isset($data->cotarFrete)){
  4756.             $entregaNova->setCotarFrete($data->cotarFrete);
  4757.         }
  4758.         
  4759.         if(isset($data->observacaoCadastro)){
  4760.             $observacao $data->observacaoCadastro;
  4761.         }
  4762.         
  4763.         if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis')) {
  4764.             
  4765.             if(isset($data->regeocodifica)){
  4766.                 if($data->regeocodifica){
  4767.                     if($enderecoEntregaParaGeocode!=''){
  4768.                         
  4769.                         $coordenadasDoEndereco $this->decodificaEndereco($enderecoEntregaParaGeocode);
  4770.                         if($coordenadasDoEndereco!==false){
  4771.                             if(isset($coordenadasDoEndereco['latitude']) && isset($coordenadasDoEndereco['longitude'])){
  4772.                                 $entregaNova->setLatitude($coordenadasDoEndereco['latitude']);
  4773.                                 $entregaNova->setLongitude($coordenadasDoEndereco['longitude']);
  4774.                                 
  4775.                                 $linkEndereco "https://waze.com/ul?ll=".$coordenadasDoEndereco['latitude'].",".$coordenadasDoEndereco['longitude']."&navigate=yes";
  4776.                                 $entregaNova->setLinkEnderecoEntrega($linkEndereco);
  4777.                                 $entregaNova->setEnderecoEntrega($enderecoEntregaParaGeocode);
  4778.                             }
  4779.                         } else {
  4780.                             return new JsonResponse(['Erro em geolocalizar'], 400);
  4781.                         }
  4782.                     }
  4783.                 }
  4784.             }
  4785.             
  4786.         }
  4787.         
  4788.         $this->getDoctrine()->getManager()->flush();
  4789.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  4790.         
  4791.     }
  4792.     
  4793.     
  4794.     /**
  4795.      * @Route("/app-externo/cadastra-entrega", name="cadastra_entrega", methods={"POST"})
  4796.      */
  4797.     public function cadastraEntrega(Request $request): Response
  4798.     {
  4799.         $data json_decode($request->getContent(), false);
  4800.         $pedidoLocalizado false;
  4801.         $enderecoEntregaParaGeocode '';
  4802.         $esperarClientePagar 'Não';
  4803.         
  4804.         if(isset($data->esperarClientePagar)) {
  4805.             $esperarClientePagar $data->esperarClientePagar;
  4806.         }
  4807.         
  4808.         if(isset($data->meioEntrega)){
  4809.             if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis') && $esperarClientePagar=='Não') {
  4810.         
  4811.                 if(!isset($data->dataEntrega)) {
  4812.                     return new JsonResponse(['message'=>'Informe a data de entrega!'], 400);
  4813.                 }
  4814.                 
  4815.                 if($data->dataEntrega=='') {
  4816.                     return new JsonResponse(['message'=>'Informe a data de entrega!'], 400);
  4817.                 }
  4818.                 
  4819.                 if($data->periodosEntrega=='lotado'){
  4820.                     return new JsonResponse(['message'=>'O período selecionado está lotado. Tente outro período.'], 400);
  4821.                 }
  4822.                 
  4823.                 // // Validar a disponibilidade por periodo na data de entrega
  4824.                 // $date = \DateTime::createFromFormat('d/m/Y', $data->dataEntrega);
  4825.                 // $totalPedidosDia    = $this->getTotalPedidosDia($date);
  4826.                 
  4827.                 // $totalPorPeriodo    = ($data->periodosEntrega=='Qualquer Horário') ? $totalPedidosDia : ($totalPedidosDia/2);
  4828.                 // $totalPedidosNaData = $this->getDoctrine()->getRepository(EntregaPedido::class)
  4829.                 //                       ->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), $data->periodosEntrega);
  4830.                                       
  4831.                 // $totalPedidosNaData = count($totalPedidosNaData); // 49337
  4832.                 
  4833.                 // exit("totalPorPeriodo $totalPorPeriodo - totalPedidosNaData: $totalPedidosNaData");
  4834.                                       
  4835.                 // if($totalPedidosNaData >= $totalPedidosDia) {
  4836.                 //     return new JsonResponse(['message'=>'Não há vaga para entregar esse pedido nessa data e nesse período!'], 400);
  4837.                 // }
  4838.                 
  4839.             }
  4840.         }
  4841.         
  4842.         if(isset($data->tipo)) {
  4843.             if($data->tipo=='nf') {
  4844.                 $pedidoId intval($data->numeroNf);
  4845.                 $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$pedidoId'deletedAt'=>null]);
  4846.             } else {
  4847.                 $pedidoId intval($data->numeroPedido);
  4848.                 $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoId'deletedAt'=>null]);
  4849.                 // if(!$pedido instanceof EntregaPedido) {
  4850.                 //     $pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoId.'-Assistência']);
  4851.                 // }
  4852.             }
  4853.         }
  4854.         
  4855.         if($pedido instanceof EntregaPedido) {
  4856.             
  4857.             return new JsonResponse(['message'=>'Este pedido já existe no sistema #1.'], 400);
  4858.             
  4859.             // if(!$this->isAdmin() && !$this->getIsVendedor()) {
  4860.             //     return new JsonResponse(['message'=>'Este pedido já existe no sistema.'], 400);
  4861.             // }
  4862.             
  4863.             $pedidoLocalizado true;
  4864.             $entregaNova $pedido;
  4865.         } else {
  4866.             $entregaNova = new EntregaPedido();
  4867.         }
  4868.         
  4869.         // validações somente para cadastro de vendedor
  4870.         // if($this->getIsVendedor()) {
  4871.         //     if(
  4872.         //         ($data->assistencia=='Sim' && $data->periodosEntrega=='' && $data->meioEntrega=='') /* Validações assistencia */
  4873.         //         ||
  4874.         //         ($data->assistencia=='Não' && $data->periodosEntrega=='' && $data->meioEntrega=='' && 
  4875.         //         $data->formaPagamento=='' && $data->periodosEntrega=='') /* Validações não assistencia */
  4876.         //     ) {
  4877.         //         return new JsonResponse(['message'=>'Todos os campos do formulário são obrigatórios para o cadastro do pedido.'], 400);
  4878.         //     }
  4879.         // }
  4880.         
  4881.         // if(isset($cliente['endereco'])) {
  4882.         //     if($cliente['endereco']!='') {
  4883.                 
  4884.         //         $entregaNova->setEndereco($cliente['endereco']);
  4885.         //         $enderecoEntregaParaGeocode = $cliente['endereco'];
  4886.         //     }
  4887.         // }
  4888.         
  4889.         if(isset($data->endereco) && $data->endereco!=''){
  4890.             $entregaNova->setEndereco($data->endereco);
  4891.             $enderecoEntregaParaGeocode $data->endereco;
  4892.         }
  4893.         
  4894.         if(isset($data->endereco_entrega) && $data->endereco_entrega!=''){
  4895.             $entregaNova->setEndereco($data->endereco_entrega);
  4896.             $enderecoEntregaParaGeocode $data->endereco_entrega;
  4897.         }
  4898.         
  4899.         $numeroNf '';
  4900.         $numeroPedido '';
  4901.         
  4902.         if($data->numeroPedido=='') {
  4903.             $numeroPedido $data->numeroNf;
  4904.             $numeroNf $data->numeroNf;
  4905.         }
  4906.         
  4907.         if($data->numeroNf=='') {
  4908.             $numeroNf '';
  4909.             $numeroPedido $data->numeroPedido;
  4910.         } else {
  4911.             $numeroNf $data->numeroNf;
  4912.             $numeroPedido $data->numeroPedido;
  4913.         }
  4914.         
  4915.         //$numeroTelefone = preg_replace('/[^0-9]/', '', $data->telefone);
  4916.         //$numeroTelefone ='55' . $numeroTelefone;
  4917.         
  4918.         $user $this->getUser();
  4919.         
  4920.         $entregaNova->setIsEntregue(false);
  4921.         $entregaNova->setStatus('pendente');
  4922.         $entregaNova->setCreatedAt(new \DateTime('now'));
  4923.         $entregaNova->setPedido($numeroPedido);
  4924.         $entregaNova->setTelefone($data->telefone);
  4925.         $entregaNova->setTipoBuscaCadastro($data->tipo);
  4926.         $entregaNova->setNotaFiscal($numeroNf);
  4927.         //$entregaNova->setEndereco($data->endereco);
  4928.         $entregaNova->setVendedor($data->vendedor);
  4929.         $entregaNova->setCadastradoPor($user->getNome());
  4930.         $entregaNova->setUpdatedAt(new \DateTime('now'));
  4931.         
  4932.         if(isset($data->itens)){
  4933.             if($data->itens!=''){
  4934.                 $entregaNova->setItensPedido(json_encode($data->itens));
  4935.             }
  4936.         }
  4937.         // Atualiza ultima movimentação de status
  4938.         $entregaNova->setLastUpdateStatus(new \DateTime('now'));
  4939.         
  4940.         $urgente false;
  4941.         if(isset($data->isUrgente)) {
  4942.             $urgente = ($data->isUrgente=='Sim') ? true false;
  4943.         }
  4944.         
  4945.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4946.             if(isset($data->montagem)) {
  4947.                $entregaNova->setMontagem($data->montagem);
  4948.             }
  4949.         }
  4950.         
  4951.         if(isset($data->separarMontarPedido)) {
  4952.             $entregaNova->setSepararMontarPedido($data->separarMontarPedido);
  4953.         }
  4954.         
  4955.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4956.             if(isset($data->assistencia)) {
  4957.                 $entregaNova->setAssistencia($data->assistencia);
  4958.             }
  4959.         }
  4960.         
  4961.         if(isset($data->tipoDocumento)) {
  4962.             $entregaNova->setTipoDocumento($data->tipoDocumento);
  4963.         }
  4964.         
  4965.         if(isset($data->origemMontagem)) {
  4966.             $entregaNova->setOrigemMontagem($data->origemMontagem);
  4967.         }
  4968.         
  4969.         if(isset($data->formaPagamento)) {
  4970.             $entregaNova->setFormaPagamento($data->formaPagamento);
  4971.         }
  4972.         if($this->getIsVendedor() || $this->getIsAdmin()){
  4973.             if(isset($data->periodosEntrega)) {
  4974.                 $entregaNova->setPeriodoEntrega($data->periodosEntrega);
  4975.                 
  4976.                 if(isset($data->horarioEntrega)) {
  4977.                     $horario = \DateTime::createFromFormat('H:i'$data->horarioEntrega);
  4978.                     $entregaNova->setHorarioEntrega($horario);
  4979.                 }
  4980.             }
  4981.         }
  4982.         
  4983.         if(isset($data->meioEntrega)) {
  4984.             $entregaNova->setMeioEntrega($data->meioEntrega);
  4985.         }
  4986.         
  4987.         if(isset($data->montarMoveis)) {
  4988.             $entregaNova->setMontarMoveis($data->montarMoveis);
  4989.         }
  4990.         
  4991.         $entregaNova->setIsUrgente($urgente);
  4992.         
  4993.         if(isset($data->observacaoCadastro)){
  4994.             $entregaNova->setObservacaoCadastro($data->observacaoCadastro);
  4995.         }
  4996.         
  4997.         if(isset($data->logradouro)){
  4998.             
  4999.             if($data->logradouro!=''){
  5000.                 
  5001.                 $endereco $data->logradouro;
  5002.             
  5003.                 if(isset($data->enderecoComplemento)){
  5004.                     if($data->enderecoComplemento!=''){
  5005.                         $endereco .= ', ' $data->enderecoComplemento ',  CEP: ' $data->cepBusca;
  5006.                     }
  5007.                 }
  5008.                 
  5009.                 $entregaNova->setNovoEnderecoEntrega($endereco);
  5010.                 $entregaNova->setEnderecoEntrega($endereco);
  5011.                 $enderecoEntregaParaGeocode $endereco;
  5012.                 
  5013.             }
  5014.             
  5015.         }
  5016.         
  5017.         if(isset($data->enderecoPadraoGoogle)){
  5018.             
  5019.             if($data->enderecoPadraoGoogle!=''){
  5020.                 $entregaNova->setNovoEnderecoEntrega($data->enderecoPadraoGoogle);
  5021.                 $entregaNova->setEnderecoEntrega($data->enderecoPadraoGoogle);
  5022.                 $enderecoEntregaParaGeocode $data->enderecoPadraoGoogle;
  5023.             }
  5024.             
  5025.         }
  5026.         
  5027.         if(isset($data->pontoReferencia)){
  5028.             
  5029.             if($data->pontoReferencia!=''){
  5030.                 $entregaNova->setEnderecoPontoReferencia($data->pontoReferencia);
  5031.             }
  5032.             
  5033.         }
  5034.         
  5035.         $entregaNova->setContato($data->contato);
  5036.         
  5037.         if(isset($data->tipoFrete)){
  5038.             $entregaNova->setTipoFrete($data->tipoFrete);
  5039.         }
  5040.         
  5041.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5042.             if(isset($data->embalagem)){
  5043.                 $entregaNova->setEmbalagem($data->embalagem);
  5044.             }
  5045.         }
  5046.         
  5047.         if(!$pedidoLocalizado){
  5048.             $this->getDoctrine()->getManager()->persist($entregaNova); 
  5049.         }
  5050.         
  5051.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5052.             if(isset($data->estaPago)){
  5053.                 $entregaNova->setEstaPago($data->estaPago);
  5054.             } else {
  5055.                 $entregaNova->setEstaPago("Não");
  5056.             }
  5057.         }
  5058.         
  5059.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5060.             if(isset($data->receberNaEntrega)){
  5061.                 $entregaNova->setReceberNaEntrega($data->receberNaEntrega);
  5062.             } else {
  5063.                 $entregaNova->setReceberNaEntrega("Não");
  5064.             }
  5065.         }
  5066.         
  5067.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5068.             if(isset($data->despacharTrocar)){
  5069.                 $entregaNova->setDespacharTrocar($data->despacharTrocar);
  5070.             }
  5071.         }
  5072.         
  5073.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5074.             if(isset($data->ladoMontagemBalcao) && $data->ladoMontagemBalcao!=''){
  5075.                 $entregaNova->setLadoMontagemBalcao($data->ladoMontagemBalcao);
  5076.             }
  5077.         }
  5078.         
  5079.         if(isset($data->estaPagoLoja)){
  5080.             $entregaNova->setPagoNaLoja($data->estaPagoLoja);
  5081.         }
  5082.         
  5083.         if(isset($data->cnpj)){
  5084.             $entregaNova->setCnpj($data->cnpj);
  5085.         }
  5086.         
  5087.         if(isset($data->linkEnderecoEntrega)){
  5088.             $entregaNova->setLinkEnderecoEntrega($data->linkEnderecoEntrega);
  5089.         }
  5090.         
  5091.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5092.             if(isset($data->entregarHoje)) {
  5093.                 
  5094.                 $entregaNova->setEntregarHoje($data->entregarHoje);
  5095.                 
  5096.                 if($data->entregarHoje=='Agendar') {
  5097.                     
  5098.                     if(isset($data->dataEntrega)) {
  5099.                         $dataEntrega = \DateTime::createFromFormat('Y-m-d'$data->dataEntrega);
  5100.                         $dataEntrega->setTime(235959);
  5101.                         if($dataEntrega instanceof \DateTime) {
  5102.                             $entregaNova->setDataEntrega($dataEntrega);
  5103.                         }
  5104.                     }
  5105.     
  5106.                 }
  5107.             }
  5108.         }
  5109.         
  5110.         if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis') && $esperarClientePagar=='Não') {
  5111.             
  5112.             if(isset($data->dataEntrega)) {
  5113.                 $dataEntrega = \DateTime::createFromFormat('d/m/Y'$data->dataEntrega);
  5114.                 $dataEntrega->setTime(235959);
  5115.                 if($dataEntrega instanceof \DateTime) {
  5116.                     $entregaNova->setDataEntrega($dataEntrega);
  5117.                 }
  5118.             }
  5119.         }
  5120.         
  5121.         if(isset($data->linkShare)) {
  5122.             $entregaNova->setLinkShare($data->linkShare);
  5123.         }
  5124.         
  5125.         if($this->getIsVendedor() || $this->getIsAdmin()){
  5126.             
  5127.             if(isset($data->desejaEnviarZapSeparador)){
  5128.                 
  5129.                 if(isset($data->meioEntrega) && isset($data->desejaEnviarZapSeparador)){
  5130.                     
  5131.                     $entregaNova->setDesejaEnviarZapSeparador($data->desejaEnviarZapSeparador);
  5132.                     
  5133.                     if($data->desejaEnviarZapSeparador=='Sim'){
  5134.     
  5135.                         $type='text';
  5136.                         $montarOuNao "";
  5137.                         
  5138.                         // estaPago => Mostrar label
  5139.                         // receberNaEntrega => Mostrar label
  5140.                         // pagoNaLoja => Mostrar label
  5141.                         // desejaEnviarZapSeparador => Veriicar para mandar com link do pedido para os separadorres Link do bling
  5142.                         
  5143.                         // Chegou um novo *pedido Nº xxx* para separação. 
  5144.                             // Não montar. Usar Embalagem
  5145.                             // Favor Montar os itens
  5146.                         
  5147.                         // São jose
  5148.                             // Geovair => 5562993602042
  5149.                             // Mateus => 5562981352530
  5150.                             
  5151.                             
  5152.                             // Marcos => 5562994721501
  5153.                             
  5154.                         // Coimbra
  5155.                             // Ronald => 5562993771776
  5156.                             // Fabio => 5562999720813
  5157.                             
  5158.                             // João Marcos => 5562994542599
  5159.                             
  5160.                         
  5161.                         
  5162.                         $destinatariosSaoJose = ['5562993602042'];
  5163.                         $destinatariosCoimbra = [];
  5164.                         
  5165.                         $destinatariosTodos array_merge($destinatariosSaoJose,$destinatariosCoimbra);
  5166.                         
  5167.                         if($data->meioEntrega=='Retirar no Galpão Coimbra') {
  5168.                             $destinatarios $destinatariosCoimbra// Coimbra
  5169.                         } else if($data->meioEntrega=='Retirar no Galpão São José') {
  5170.                             $destinatarios $destinatariosSaoJose// São José
  5171.                         } else {
  5172.                             $destinatarios $destinatariosTodos;
  5173.                         }
  5174.                         
  5175.                         if($data->contato){
  5176.                             $montarOuNao .= "*Nome:* {$data->contato}\n\n";
  5177.                         }
  5178.                         
  5179.                         if($entregaNova->getIsUrgente()){
  5180.                             $montarOuNao .= "*URGENTE!*\n\n";
  5181.                         }
  5182.                         
  5183.                         if(isset($data->tipoDocumento)){
  5184.                             $montarOuNao .= "*Emitir*: " $data->tipoDocumento."\n\n";
  5185.                         }
  5186.                         
  5187.                         if(isset($data->montarMoveis)) {
  5188.                             
  5189.                             if($data->montarMoveis=='Não') {
  5190.                                 if(isset($data->embalagem)) {
  5191.                                     $montarOuNao .= "*Montar Móveis*: Não \n\n*Usar a embalagem:* " $data->embalagem "\n\n"
  5192.                                 } else {
  5193.                                     $montarOuNao .= "*Montar Pedido*: Não\n\n";
  5194.                                     $montarOuNao .= "*Montagem*: ".$data->montarMoveis."\n\n";
  5195.                                 }
  5196.                             } else {
  5197.                                 $montarOuNao .= "*Montar Móveis*: Sim\n\n";
  5198.                                 
  5199.                                 if(isset($data->ladoMontagemBalcao) && $data->ladoMontagemBalcao != ''){
  5200.                                     $montarOuNao .= "*Lado Balcão*: {$data->ladoMontagemBalcao}\n\n";
  5201.                                 }
  5202.                                 
  5203.                                 $montarOuNao .= "*Montagem*: ".$data->montarMoveis."\n\n";
  5204.                             }
  5205.                             
  5206.                             
  5207.                         } else {
  5208.                             $montarOuNao .= "*Montar Móveis*: Não\n\n";
  5209.                             if(isset($data->montarMoveis)){
  5210.                                $montarOuNao .= "*Montagem*: ".$data->montarMoveis."\n\n"
  5211.                             }
  5212.                         }
  5213.                         
  5214.                     //   if($entregaNova->getSepararMontarPedido()){
  5215.                     //         $montarOuNao .= "*Separar ou Montar Pedido*: ".$entregaNova->getSepararMontarPedido()."\n";
  5216.                     //     } else {
  5217.                     //         $montarOuNao .= "*Separar ou Montar Pedido*: Não \n";
  5218.                     //     }
  5219.                         
  5220.     
  5221.                         if($entregaNova->getEntregarHoje()=='Agendar') {
  5222.                             $montarOuNao .= "*Data da Entrega*: " $entregaNova->getDataEntrega()->format('d/m/Y') . "\n\n";
  5223.                         } else {
  5224.                             
  5225.                             if(isset($data->montarMoveis)){
  5226.                                 if($data->montarMoveis!='Sim' && $data->montarMoveis!='Não'){
  5227.                                     $montarOuNao .= "*Entregar Hoje*: ".$entregaNova->getEntregarHoje()." \n\n";    
  5228.                                 }
  5229.                             }
  5230.                         }
  5231.                         
  5232.                         if($entregaNova->getPeriodoEntrega()!="Agendar Horário") {
  5233.                             $montarOuNao .= "*Período da Entrega*: " $entregaNova->getPeriodoEntrega() . "\n\n";
  5234.                         }
  5235.                         
  5236.                         if($entregaNova->getEntregarHoje()=='Agendar') {
  5237.                             if($entregaNova->getPeriodoEntrega()=="Agendar Horário") {
  5238.                                 $montarOuNao .= "*Horário da Entrega*: " $entregaNova->getHorarioEntrega()->format('H:i') . "\n\n";
  5239.                             }
  5240.                         }
  5241.      
  5242.                         $montarOuNao .= "*Observações*: " $entregaNova->getObservacaoCadastro();
  5243.                         
  5244.                         if($numeroPedido=='') {
  5245.                             $numeroPedido $numeroNf;
  5246.                             $messageBody "Chegou um novo *pedido com NF: $numeroPedido* para separação.\n\n$montarOuNao\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5247.                         } else {
  5248.                             $messageBody "Chegou um novo *pedido Nº $numeroPedido* para separação.\n\n$montarOuNao\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5249.                         }
  5250.                         
  5251.                         //if($data->numeroNf=='') {
  5252.                             $messageBody $messageBody "\n\n" 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $numeroPedido;
  5253.                         //}
  5254.                         
  5255.                         //$destinatarios = ['556291089053', '5562983281823']; // TESTE
  5256.                        
  5257.                         foreach ($destinatarios as $destinatario) {
  5258.                             $this->sendMensagemViaWhatsapp($type$destinatario$messageBodynullnullnull);
  5259.                         }
  5260.                     }
  5261.     
  5262.                 }
  5263.                 
  5264.             }
  5265.             
  5266.         }
  5267.         
  5268.         if(isset($data->cotarFrete)){
  5269.             $entregaNova->setCotarFrete($data->cotarFrete);
  5270.             if($data->cotarFrete=='Sim'){
  5271.                 $messageBody "Favor cotar o valor do frete do *pedido Nº: $numeroPedido*\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5272.                 $this->sendMensagemViaWhatsapp('text''5562993126267'$messageBodynullnullnull); // Guilherme
  5273.                 //$this->sendMensagemViaWhatsapp('text', '556291089053', $messageBody, null, null, null); // TESTE
  5274.             }
  5275.         }
  5276.         
  5277.         if(isset($data->solicitarColeta)) {
  5278.             $entregaNova->setSolicitarColeta($data->solicitarColeta);
  5279.             if($data->solicitarColeta=='Sim'){
  5280.                 
  5281.                 if(isset($data->nomeTrasportadora)) {
  5282.                     
  5283.                     if($data->nomeTrasportadora==''){
  5284.                         return new JsonResponse(['mensagem'=>'Nesse caso o nome da transportadora é obrigatório.'], 400);
  5285.                     } else {
  5286.                         $entregaNova->setNomeTransportadora($data->nomeTrasportadora);
  5287.                         $messageBody "Favor solicitar a *COLETA* do *pedido Nº: $numeroPedido*.\n\n*Transportadora:* " $data->nomeTrasportadora "\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5288.                         $this->sendMensagemViaWhatsapp('text''5562993126267'$messageBodynullnullnull); // Guilherme
  5289.                     }
  5290.                     
  5291.                 } else {
  5292.                     return new JsonResponse([], 400);
  5293.                 }
  5294.             }
  5295.         }
  5296.         
  5297.         if(isset($data->desejaEnviarZapGuilherme)) {
  5298.             if($data->desejaEnviarZapGuilherme=='Sim') {
  5299.                 
  5300.                 $messageBody "Favor enviar a mercadoria pelos Correios. *Pedido Nº: $numeroPedido*" "\n\n" 
  5301.                 "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5302.                 
  5303.                 $this->sendMensagemViaWhatsapp('text''5562993126267'$messageBodynullnullnull);
  5304.             }
  5305.         }
  5306.         
  5307.         $contato $data->contato;
  5308.         $observacao "";
  5309.         $numeroPedido = ($entregaNova->getPedido()!='') ? $entregaNova->getPedido() : $entregaNova->getNotaFiscal();
  5310.         
  5311.         if(isset($data->observacaoCadastro)){
  5312.             $observacao $data->observacaoCadastro;
  5313.         }
  5314.         
  5315.         if($observacao!='') {
  5316.             // Envio zap benjamim
  5317.             $messageBody "*Uhuul!* Chegou um pedido novo N *$numeroPedido*. Favor dar andamento!\n\nNome/Razão Social: $contato\n\nObservação: *$observacao*\n\nLink Pedido: " $linkPedido 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $numeroPedido "\n\n" "Acesso o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5318.             
  5319.             if($data->tipo=='pedido_entregue'){
  5320.                  $messageBody "*PEDIDO ENTREGUE*\n\nPedido N *$numeroPedido* inserido na API. Apenas para possível andamento!\n\nNome/Razão Social: $contato\n\nObservação: *$observacao*\n\nLink Pedido: " $linkPedido 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $numeroPedido "\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5321.             }
  5322.             
  5323.         } else {
  5324.             // Envio zap benjamim
  5325.             $messageBody "*Uhuul!* Chegou um pedido novo N *$numeroPedido* inserido na API. Favor dar andamento!\n\nNome/Razão Social: $contato\n\nLink Pedido: " $linkPedido 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $numeroPedido "\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5326.             
  5327.             if($data->tipo=='pedido_entregue'){
  5328.                $messageBody "*PEDIDO ENTREGUE*\n\nPedido N *$numeroPedido* inserido na API. Apenas para possível andamento!\n\nNome/Razão Social: $contato\n\nLink Pedido: " $linkPedido 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $numeroPedido
  5329.             }
  5330.             
  5331.         }
  5332.         
  5333.         $entregaNova->setCodidoRastreio($this->geraCodigoRastreio());
  5334.         
  5335.         if($data->tipo!='mkplace') {
  5336.             
  5337.             if($data->tipo!='pedido_entregue'){
  5338.                 $this->notificaClienteCriacaoCard($entregaNova); 
  5339.             }
  5340.             //$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // Benjamim
  5341.             //$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
  5342.             $this->sendMensagemViaWhatsapp("text""556291089053"$messageBodynullnullnull); // Bruno
  5343.             //$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
  5344.             //$this->sendMensagemViaWhatsapp("text", "5562981352530", $messageBody, null, null, null); // Mateus
  5345.             
  5346.             
  5347.         }
  5348.         
  5349.         if($data->tipo=='mkplace'){
  5350.             $entregaNova->setStatus('baixado');
  5351.         }
  5352.         
  5353.         if($data->tipo=='pedido_entregue'){
  5354.             $entregaNova->setStatus('entregue');
  5355.         }
  5356.         
  5357.         if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis')) {
  5358.             if($enderecoEntregaParaGeocode!=''){
  5359.                 
  5360.                 $coordenadasDoEndereco $this->decodificaEndereco($enderecoEntregaParaGeocode);
  5361.                 if($coordenadasDoEndereco!==false){
  5362.                     if(isset($coordenadasDoEndereco['latitude']) && isset($coordenadasDoEndereco['longitude'])){
  5363.                         $entregaNova->setLatitude($coordenadasDoEndereco['latitude']);
  5364.                         $entregaNova->setLongitude($coordenadasDoEndereco['longitude']);
  5365.                         
  5366.                         $linkEndereco "https://waze.com/ul?ll=".$coordenadasDoEndereco['latitude'].",".$coordenadasDoEndereco['longitude']."&navigate=yes";
  5367.                         $entregaNova->setLinkEnderecoEntrega($linkEndereco);
  5368.                         $entregaNova->setEnderecoEntrega($enderecoEntregaParaGeocode);
  5369.                     }
  5370.                 }
  5371.             }
  5372.         }
  5373.         
  5374.         $this->getDoctrine()->getManager()->flush();
  5375.     
  5376.         $isUrgente $urgente;
  5377.         $clienteVaiBuscarImediatamente false;
  5378.         if(isset($data->entregarHoje)){
  5379.             $clienteVaiBuscarImediatamente = ($data->entregarHoje=='Cliente Vai Retirar Imediatamente') ? true false;
  5380.         }
  5381.         if(isset($data->montarMoveis)) {
  5382.             
  5383.             if($data->montarMoveis=='Não') {
  5384.                 if($data->origemMontagem=='Galpão Coimbra') {
  5385.                     $this->createDemandaPedido($entregaNova'co''separacao'true$clienteVaiBuscarImediatamente$isUrgente);
  5386.                 } else if($data->origemMontagem=='Galpão São José') {
  5387.                     $this->createDemandaPedido($entregaNova'sj''separacao'true$clienteVaiBuscarImediatamente$isUrgente);
  5388.                 } else { // Galpão Coimbra/Galpão São José
  5389.                     $this->createDemandaPedido($entregaNova'co''separacao'true$clienteVaiBuscarImediatamente$isUrgente);
  5390.                     $this->createDemandaPedido($entregaNova'sj''separacao'true$clienteVaiBuscarImediatamente$isUrgente);
  5391.                 }
  5392.             
  5393.             } else {
  5394.                 
  5395.                 if($data->origemMontagem=='Galpão Coimbra'){
  5396.                     $this->createDemandaPedido($entregaNova'co''montagem'true$clienteVaiBuscarImediatamente$isUrgente);
  5397.                 } else if($data->origemMontagem=='Galpão São José') {
  5398.                     $this->createDemandaPedido($entregaNova'sj''montagem'true$clienteVaiBuscarImediatamente$isUrgente);
  5399.                 } else { // Galpão Coimbra/Galpão São José
  5400.                     $this->createDemandaPedido($entregaNova'co''montagem'true$clienteVaiBuscarImediatamente$isUrgente);
  5401.                     $this->createDemandaPedido($entregaNova'sj''montagem'true$clienteVaiBuscarImediatamente$isUrgente);
  5402.                 }
  5403.                 
  5404.             }
  5405.         }
  5406.         
  5407.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  5408.         
  5409.     }
  5410.     
  5411.     private function geraCodigoRastreio(){
  5412.         $caracteres '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
  5413.         $codigo '';
  5414.     
  5415.         for ($i 0$i 12$i++) {
  5416.             $codigo .= $caracteres[rand(0strlen($caracteres) - 1)];
  5417.         }
  5418.     
  5419.         return $codigo;
  5420.     }
  5421.     
  5422.     /**
  5423.      * @Route("/app-externo/deletar-entrega", name="deletar_entrega", methods={"POST"})
  5424.      */
  5425.     public function deletarPedido(Request $request): Response
  5426.     {
  5427.         
  5428.         if($this->getUser()->getEmail()!='bruno@moveispollo.com.br') {
  5429.             return new JsonResponse(['message'=>'Não é possível excluir'], 400);
  5430.         }
  5431.         
  5432.         $data json_decode($request->getContent(), false);
  5433.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5434.         
  5435.         if(!$pedido instanceof EntregaPedido) {
  5436.             return new JsonResponse([], 400);
  5437.         }
  5438.         
  5439.         if($pedido->getRoute()!=null){
  5440.             return new JsonResponse($this->todosPedidosPorStatus(), 201);
  5441.         }
  5442.         
  5443.         $pedido->setDeletedAt(new \DateTime('now'));
  5444.         //$this->getDoctrine()->getManager()->remove($pedido);
  5445.         $this->getDoctrine()->getManager()->flush();
  5446.         
  5447.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  5448.         
  5449.     }
  5450.     
  5451.         /**
  5452.      * @Route("/app-externo/informar-localizacao", name="informar_localizacao", methods={"POST"})
  5453.      */
  5454.     public function informarLocalizacao(Request $request): Response
  5455.     {
  5456.         $data json_decode($request->getContent(), false);
  5457.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5458.         
  5459.         if(!$pedido instanceof EntregaPedido){
  5460.             return new JsonResponse($pedidosData400);
  5461.         }
  5462.         $pedido->setLocalizacao($data->localizacao);
  5463.         
  5464.         if($data->localizacao=='limpar' || $data->localizacao=='apagar'){
  5465.             $pedido->setLocalizacao(null);
  5466.         }
  5467.         
  5468.         $this->getDoctrine()->getManager()->flush();
  5469.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  5470.         
  5471.     }
  5472.     
  5473.     /**
  5474.      * @Route("/app-externo/informar-obs", name="informmar_obs", methods={"POST"})
  5475.      */
  5476.     public function informarObs(Request $request): Response
  5477.     {
  5478.         $data json_decode($request->getContent(), false);
  5479.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5480.         
  5481.         if(!$pedido instanceof EntregaPedido){
  5482.             return new JsonResponse($pedidosData400);
  5483.         }
  5484.         
  5485.         $user $this->getUser();
  5486.         $pedido->setIsObsLida(false);
  5487.         
  5488.         $dataHora = new \DateTime('now');
  5489.         
  5490.         if($data->obs!="") {
  5491.             $obs ='<span style="color: red">' $user->getNome() . ' em ' $dataHora->format('d/m/Y H:i') .'</span>: <span style="word-break: break-all;">' $data->obs '</span>';
  5492.             if($pedido->getObsVendedor() != '') {
  5493.                 $obs $pedido->getObsVendedor() . ' - ' $obs;
  5494.                 $pedido->setObsVendedor($obs);
  5495.             } else {
  5496.                 $pedido->setObsVendedor($obs);
  5497.             }
  5498.         }
  5499.         
  5500.         if(strtolower(trim($data->obs))=='limpar') {
  5501.             $pedido->setObsVendedor('');
  5502.         } else {
  5503.             
  5504.             $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  5505.             
  5506.             $linkPedido 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' $numeroPedido;
  5507.             
  5508.             $messageBody 
  5509.             "*OBSERVAÇÃO LANÇADA* no pedido/NF: $numeroPedido\n\nNome: {$pedido->getContato()}\n\nObservação: {$user->getNome()}: *{$data->obs}*\n\nLink Pedido: " $linkPedido "\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5510.             
  5511.             //$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // benjamim
  5512.             //$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
  5513.             $this->sendMensagemViaWhatsapp("text""556291089053"$messageBodynullnullnull); // Bruno
  5514.             //$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
  5515.             
  5516.             if($pedido->getColaboradorUser()!='' && $pedido->getColaboradorUser()!=null) {
  5517.                 $telefoneMotorista $pedido->getColaboradorUser()->getTelefone();
  5518.                 $this->sendMensagemViaWhatsapp("text"$telefoneMotorista$messageBodynullnullnull);
  5519.             }
  5520.             
  5521.             if($pedido->getStatus()=='pendente' || $pedido->getStatus()=='recebido' || $pedido->getStatus()=='aceito'){
  5522.                 if($pedido->getSeparador()!='' && $pedido->getSeparador()!=null){
  5523.                     $usarioSeparador $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$pedido->getSeparador()]);
  5524.                     if($usarioSeparador instanceof User) {
  5525.                         $this->sendMensagemViaWhatsapp("text"$usarioSeparador->getTelefone(), $messageBodynullnullnull);
  5526.                     }
  5527.                 }
  5528.             }
  5529.         
  5530.             // Envio zap vendedor
  5531.             $usuarioVendedor strtolower($pedido->getVendedor());
  5532.             $usarioVendedor $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioVendedor]);
  5533.             if($usarioVendedor instanceof User){
  5534.                 $telefone $usarioVendedor->getTelefone();
  5535.                 
  5536.                 $destino 'W';
  5537.                 if($telefone=='556232337424') {
  5538.                     $destino 'B';
  5539.                 }
  5540.                 $this->sendMensagemViaWhatsapp("text"$telefone$messageBodynullnullnull$destino);
  5541.             }
  5542.             
  5543.             // Envio zap Cadastrante
  5544.             $usuarioCadastrante strtolower($pedido->getCadastradoPor());
  5545.             $usuarioCadastrante $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioCadastrante]);
  5546.             if($usuarioCadastrante instanceof User){
  5547.                 $telefone $usuarioCadastrante->getTelefone();
  5548.                 
  5549.                 $destino 'W';
  5550.                 if($telefone=='556232337424') {
  5551.                     $destino 'B';
  5552.                 }
  5553.                 $this->sendMensagemViaWhatsapp("text"$telefone$messageBodynullnullnull$destino);
  5554.             }
  5555.             
  5556.         }
  5557.         
  5558.         $this->getDoctrine()->getManager()->flush();
  5559.         
  5560.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  5561.     }
  5562.     
  5563.     /**
  5564.      * @Route("/app-externo/informar-tratativa", name="informmar_tratativa", methods={"POST"})
  5565.      */
  5566.     public function informarTratativa(Request $request): Response
  5567.     {
  5568.         $data json_decode($request->getContent(), false);
  5569.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5570.         
  5571.         if(!$pedido instanceof EntregaPedido){
  5572.             return new JsonResponse($pedidosData400);
  5573.         }
  5574.         
  5575.         $pedido->setTratativa($data->tratativa);
  5576.         $this->getDoctrine()->getManager()->flush();
  5577.         
  5578.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  5579.     }
  5580.     
  5581.     /**
  5582.      * @Route("/app-externo/informar-problema", name="informmar_problema", methods={"POST"})
  5583.      */
  5584.     public function informarProblema(Request $request): Response
  5585.     {
  5586.         $data json_decode($request->getContent(), false);
  5587.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5588.         
  5589.         $todosPedidos = (!$this->getUser() instanceof User) ? [] : $this->todosPedidosPorStatus();
  5590.         
  5591.         if(!$pedido instanceof EntregaPedido){
  5592.             return new JsonResponse($todosPedidos201);
  5593.         }
  5594.         
  5595.         // É para manter os dados de problema no card original?
  5596.         $pedidoENF $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$pedido->getPedido(),'deletedAt'=>null]);
  5597.         if(!$pedidoENF instanceof EntregaPedido){
  5598.                     
  5599.             $pedidoExistente $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedido->getPedido().'-Assistência''deletedAt'=>null]);
  5600.             
  5601.             if($pedidoExistente instanceof EntregaPedido) {
  5602.                 return new JsonResponse($todosPedidos201);
  5603.                 
  5604.             }
  5605.             
  5606.         }
  5607.         
  5608.         $dataPedidoEntrega = \DateTime::createFromFormat('Y-m-d'$data->data_entrega_assistencia);
  5609.         $novoPedido = clone $pedido;
  5610.         //$novoPedido->setId(null);
  5611.         $novoPedido->setPedido($pedido->getPedido().'-Assistência');
  5612.         
  5613.         $novoPedido->setProblema($data->problema);
  5614.         $novoPedido->setProblemaObs($data->obs);
  5615.         $novoPedido->setStatus('pendente');
  5616.         $novoPedido->setCreatedAt(new \DateTime('now'));
  5617.         $novoPedido->setUpdatedAt(new \DateTime('now'));
  5618.         $usuarioNome = (!$this->getUser() instanceof User) ? 'Acesso público' $this->getUser()->getNome();
  5619.         $novoPedido->setCadastradoPor($usuarioNome);
  5620.         
  5621.         if($data->problema=='COLETA REVERSA') {
  5622.             
  5623.             $novoPedido->setReversaNomeCliente($data->reversa_nome_cliente);
  5624.             $novoPedido->setReversaContatoCliente($data->reversa_contato_cliente);
  5625.             $novoPedido->setReversaEndereco($data->reversa_endereco);
  5626.             $novoPedido->setReversaVolume($data->reversa_volume);
  5627.             $novoPedido->setMercadoriaEmbalada($data->reversa_embalada);
  5628.         }
  5629.         
  5630.         if($data->problema=='DEVOLUCAO DE VALORES') {
  5631.             
  5632.             $valor preg_replace("/[^0-9,.]/"""$data->devolucao_de_valores__valor_extorno);
  5633.             $valor str_replace("."""$valor);
  5634.             $valor str_ireplace(',','.'$valor);
  5635.             
  5636.             $novoPedido->setDevolucaoValoresForma($data->devolucao_de_valores__forma_extorno);
  5637.             $novoPedido->setDevolucaoValoresValor($valor);
  5638.             $novoPedido->setDevolucaoValoresMotivo($data->devolucao_de_valores__motivo_extorno);
  5639.             $novoPedido->setDevolucaoValoresChavePix($data->devolucao_de_valores__chave_pix_extorno);
  5640.             
  5641.             $dataDevolucaoValores explode('-'$data->devolucao_de_valores__data_pagamento_cliente_extorno);
  5642.             $novoPedido->setDevolucaoValoresDataCliente("{$dataDevolucaoValores[2]}/{$dataDevolucaoValores[1]}/{$dataDevolucaoValores[0]}");
  5643.             
  5644.         }
  5645.         $novoPedido->setBaixadoAt(null);
  5646.         $novoPedido->setSeparadorAceitouAt(null);
  5647.         $novoPedido->setTempoGastoSeparacao(null);
  5648.         $novoPedido->setColaboradorUser(null);
  5649.         
  5650.         $novoPedido->setPedidoRealizadoCheckAt(null);
  5651.         $novoPedido->setPedidoRealizadoCoimbraCheckAt(null);
  5652.         $novoPedido->setPedidoImpressoCheckAt(null);
  5653.         $novoPedido->setPedidoEnderecoCheckAt(null);
  5654.         $novoPedido->setPedidoMontagemCheckAt(null);
  5655.         $novoPedido->setPedidoMotoristaCheckAt(null);
  5656.         $novoPedido->setPedidoInstagramCheckAt(null);
  5657.         $novoPedido->setPedidoGoogleCheckAt(null);
  5658.         
  5659.        $novoPedido->setPedidoMontandoMontagemFinalizada(null);
  5660.        $novoPedido->setPedidoMontandoRonald(null);
  5661.        $novoPedido->setAguardandoColeta(null);
  5662.        $novoPedido->setIsColetado(null);
  5663.        $novoPedido->setDataLimiteParado(null);
  5664.        $novoPedido->setPedidoImpressoCheckAtSaoJose(null);
  5665.        $novoPedido->setPedidoImpressoGuilhermeCheck(null);
  5666.        $novoPedido->setPedidoPagoCheckAtSaoJose(null);
  5667.        $novoPedido->setPedidoRetiradoCheckAtSaoJose(null);
  5668.        $novoPedido->setPedidoCeletadoCheckAtSaoJose(null);
  5669.        $novoPedido->setPedidoFotoProdutoCheckAtSaoJose(null);
  5670.        $novoPedido->setPedidoFotoAssinaturaCheckAtSaoJose(null);
  5671.        $novoPedido->setPedidoPagoCheckAt(null);
  5672.        $novoPedido->setPedidoMontandoFabio(null);
  5673.        $novoPedido->setPedidoMontandoRian(null);
  5674.        
  5675.        $novoPedido->setSolicitarMontagem(null);
  5676.        $novoPedido->setSolicitarMontagemSaoJose(null);
  5677.        $novoPedido->setSolicitarSeparacao(null);
  5678.        $novoPedido->setSolicitarSeparacaoSaoJose(null);
  5679.         $novoPedido->setDataInicioEntrega(null);
  5680.         $novoPedido->setDataInicioEntrega(null);
  5681.         $novoPedido->setAceitoAt(null);
  5682.         $novoPedido->setObsVendedor(null);
  5683.         $novoPedido->setObservacaoCadastro(null);
  5684.         $novoPedido->setLinkEnderecoEntrega(null);
  5685.         $novoPedido->setRoute(null);
  5686.         
  5687.         $novoPedido->setEntregarAt(null);
  5688.         $novoPedido->setIsEntregue(false);
  5689.         $novoPedido->setAuxiliar('');
  5690.         $novoPedido->setFotos(null);
  5691.         $novoPedido->setNotas(null);
  5692.         $novoPedido->setFotosSinistro(null);
  5693.         $novoPedido->setFotosAssistencia(null);
  5694.         $novoPedido->setComprovantePagamento(null);
  5695.         $novoPedido->setSeparador(nulltrue);
  5696.         
  5697.         if($dataPedidoEntrega instanceof \DateTime) {
  5698.             $novoPedido->setDataEntrega($dataPedidoEntrega);
  5699.         }
  5700.         
  5701.         $novoPedido->setIsAssistencia(true);
  5702.         
  5703.         $novoPedido->setLastUpdateStatus(new \DateTime('now'));
  5704.         
  5705.         $this->getDoctrine()->getManager()->persist($novoPedido);
  5706.         $this->getDoctrine()->getManager()->flush();
  5707.         
  5708.         /*
  5709.         
  5710.         $pedido->setProblema($data->problema);
  5711.         $pedido->setProblemaObs($data->obs);
  5712.         $pedido->setStatus('pendente');
  5713.         //$pedido->setCreatedAt(new \DateTime('now'));
  5714.         $pedido->setUpdatedAt(new \DateTime('now'));
  5715.         
  5716.         $this->getDoctrine()->getManager()->flush();
  5717.         
  5718.         */
  5719.         
  5720.         $numeroPedido = ($novoPedido->getPedido()!='') ? $novoPedido->getPedido() : $novoPedido->getNotaFiscal();
  5721.         
  5722.         // Caso COLETA REVERSA
  5723.         if($data->problema=='COLETA REVERSA') {
  5724.                 
  5725.             $nomeCliente $novoPedido->getReversaNomeCliente();
  5726.             $contatoCliente $novoPedido->getReversaContatoCliente();
  5727.             $enderecoColeta $novoPedido->getReversaEndereco();
  5728.             $volume $novoPedido->getReversaVolume();
  5729.             $embalado $novoPedido->getMercadoriaEmbalada();
  5730.             
  5731.             $messageBody "*ATENÇÃO*\n\nSolicitação de *COLETA REVERSA*. Favor inserir na observação do card o número da cotação.\n\n*Pedido/NF:* $numeroPedido\n\n*Nome*: {$novoPedido->getContato()}\nMotivo: *{$data->problema}*\n\n*Nome Cliente:* $nomeCliente\n\n*Contato Cliente:* $contatoCliente\n\n*Endereço Coleta:* $enderecoColeta\n\n*Volume:*  $volume\n\n*Embalado:* $embalado\n\n*Observação:* {$data->obs}\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5732.             
  5733.             //$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
  5734.             $this->sendMensagemViaWhatsapp("text""5562993126267"$messageBodynullnullnull); // Guilherme
  5735.             
  5736.         } else if($data->problema=='DEVOLUCAO DE VALORES'){
  5737.             
  5738.             $devolucao_de_valores__forma_extorno $novoPedido->getDevolucaoValoresForma();
  5739.             $devolucao_de_valores__valor_extorno number_format($novoPedido->getDevolucaoValoresValor(), 2',''.');
  5740.             $devolucao_de_valores__motivo_extorno $novoPedido->getDevolucaoValoresMotivo();
  5741.             $devolucao_de_valores__chave_pix_extorno $novoPedido->getDevolucaoValoresChavePix();
  5742.             $devolucao_de_valores__data_pagamento_cliente_extorno $novoPedido->getDevolucaoValoresDataCliente();
  5743.                 
  5744.             $messageBody "*ATENÇÃO*\n\n*SOLICITAÇÃO DE DEVOLUÇÃO DE VALORES.*";
  5745.             
  5746.             $dados "\n\n*Motivo:* DEVOLUÇÃO DE VALORES";
  5747.             $dados .= "\n\n*Pedido/NF:* $numeroPedido";
  5748.             $dados .= "\n\n*Cliente:* {$novoPedido->getContato()}";
  5749.             
  5750.             $dados .= "\n\nForma de devolução: $devolucao_de_valores__forma_extorno";
  5751.             $dados .= "\n\nValor da devolução: $devolucao_de_valores__valor_extorno";
  5752.             
  5753.             if($devolucao_de_valores__forma_extorno=='Outros') {
  5754.                 $dados .= "\n\nChave pix da devolução: $devolucao_de_valores__chave_pix_extorno";    
  5755.             }
  5756.             
  5757.             $dados .= "\n\nMotivo da devolução: $devolucao_de_valores__motivo_extorno";
  5758.             $dados .= "\n\n*Outras observações:* {$data->obs}\n";  
  5759.             
  5760.             $dados .= "\n\nData do pagamento: $devolucao_de_valores__data_pagamento_cliente_extorno";
  5761.             
  5762.             $messageBody .= $dados;
  5763.             
  5764.             $this->sendMensagemViaWhatsapp("text""5562992933530"$messageBodynullnullnull); // benjamim
  5765.             //$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
  5766.             $this->sendMensagemViaWhatsapp("text""556291089053"$messageBodynullnullnull); // Bruno
  5767.             //$this->sendMensagemViaWhatsapp("text", "5562983281823", $messageBody, null, null, null); // Bruno P
  5768.             
  5769.             //$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
  5770.             
  5771.         } else {
  5772.             
  5773.             $messageBody "*ATENÇÃO*\n\nUm cartão foi reaberto por algum problema apresentado. Favor dar andamento na solução.\n\n*Pedido/NF:* $numeroPedido\n\n*Nome*: {$novoPedido->getContato()}\n\nMotivo: *{$data->problema}*\n\n*Observação:* {$data->obs}\n\n" "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
  5774.             
  5775.             //$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // benjamim
  5776.             //$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
  5777.             //$this->sendMensagemViaWhatsapp("text", "556291089053", $messageBody, null, null, null); // Bruno
  5778.         
  5779.             //$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
  5780.         }
  5781.         
  5782.         return new JsonResponse($todosPedidos200);
  5783.     }
  5784.     
  5785.     /**
  5786.      * @Route("/app-externo/informar-auxiliar", name="informmar_auxiliar", methods={"POST"})
  5787.      */
  5788.     public function informarAuxiliar(Request $request): Response
  5789.     {
  5790.         $data json_decode($request->getContent(), false);
  5791.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5792.         $user $this->getUser();
  5793.         
  5794.         if(!$pedido instanceof EntregaPedido){
  5795.             return new JsonResponse($pedidosData400);
  5796.         }
  5797.         
  5798.         $pedidoAssistencia strpos($pedido->getPedido(), "Assistência");
  5799.         
  5800.         if(!$this->getIsAdmin() && $pedidoAssistencia!==false){
  5801.             return new JsonResponse([], 201);
  5802.         }
  5803.         
  5804.         if($this->getIsEntregadorAux()) {
  5805.         
  5806.             $pedido->setAuxiliar($user->getEmail());
  5807.             $this->getDoctrine()->getManager()->flush();
  5808.         }
  5809.         return new JsonResponse($this->todosPedidosPorStatus(), 200);
  5810.         
  5811.     }
  5812.     
  5813.     public function criaRotaEAdicionaPedido($pedido$user=null) {
  5814.         
  5815.         if($this->getUser() instanceof User){
  5816.             if($user==null){
  5817.                 $user $this->getUser();
  5818.             }
  5819.             
  5820.             $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  5821.             $rota $this->getDoctrine()->getRepository(EntregaRoute::class)->findOneBy(['titulo'=>$user->getEmail()]);
  5822.             
  5823.             if($rota instanceof EntregaRoute){
  5824.                 
  5825.                 $pedidos $rota->getPedidos();
  5826.                 
  5827.                 if($pedidos===null || $pedidos===''){
  5828.                     $rota->setPedidos($numeroPedido);
  5829.                 } else {
  5830.                     $pedidos explode(','$pedidos);
  5831.                     if(!in_array($numeroPedido$pedidos)){
  5832.                         if(!empty($numeroPedido)){
  5833.                             $pedidos[] = $numeroPedido;
  5834.                         }
  5835.                     }
  5836.                     
  5837.                     $rota->setPedidos(implode(','$pedidos));
  5838.                 }
  5839.     
  5840.                 $pedido->setRoute($rota);
  5841.                 
  5842.                 $this->getDoctrine()->getManager()->flush();
  5843.                 
  5844.             }
  5845.         
  5846.         }
  5847.         
  5848.         
  5849.         // $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  5850.         
  5851.         // // Verifica se já 
  5852.         
  5853.         // $rota = new EntregaRoute();
  5854.         // $rota->setTitulo($user->getNome());
  5855.         // $rota->setIsFinish(false);
  5856.         // $rota->setCreatedAt(new \DateTime());
  5857.         // $rota->setDataEntrega($pedido->getDataEntrega());
  5858.         // $rota->setPedidos($numeroPedido);
  5859.         // $this->getDoctrine()->getManager()->persist($rota);
  5860.         // $this->getDoctrine()->getManager()->flush();
  5861.         
  5862.         // $pedido->setRoute($rota);
  5863.         // $this->getDoctrine()->getManager()->flush();
  5864.     }
  5865.     
  5866.     /**
  5867.      * @Route("/app-externo/informar-motorista", name="informmar_motorista", methods={"POST"})
  5868.      */
  5869.     public function informarMotorista(Request $request): Response
  5870.     {
  5871.         $data json_decode($request->getContent(), false);
  5872.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  5873.         $user $this->getUser();
  5874.         
  5875.         if(!$pedido instanceof EntregaPedido){
  5876.             return new JsonResponse($pedidosData400);
  5877.         }
  5878.         
  5879.         $pedidoAssistencia strpos($pedido->getPedido(), "Assistência");
  5880.         
  5881.         if(!$this->getIsAdmin() && $pedidoAssistencia!==false){
  5882.             return new JsonResponse(['message'=>'Você não pode informar motorista em cartão de Assistência.'], 201);
  5883.         }
  5884.         
  5885.         $isAuxiliar filter_var($data->isAuxiliarFILTER_VALIDATE_BOOLEAN);
  5886.     
  5887.         if(!$this->getIsAdmin()){
  5888.             if($this->getIsEntregador()) {
  5889.                 if($pedido->getColaboradorUser() instanceof User){
  5890.                     return new JsonResponse(['message'=>'Proibido alterar motorista em andamento. Fale com o gerenciador'], 201);
  5891.                 }
  5892.             } else if($isAuxiliar) {
  5893.                 if($pedido->getAuxiliar()!='' && $pedido->getAuxiliar()!=null){
  5894.                     return new JsonResponse(['message'=>'Proibido alterar motorista em andamento. Fale com o gerenciador'], 201);
  5895.                 }
  5896.             }
  5897.         } 
  5898.         
  5899.         //if(!$isAuxiliar) {
  5900.             
  5901.             if($this->getIsEntregador()) {
  5902.                 
  5903.                 if(!$pedido->getColaboradorUser() instanceof User){
  5904.                     $pedido->setStatus('aceito');
  5905.                     $pedido->setLastUpdateStatus(new \DateTime('now'));
  5906.                     $this->criaRotaEAdicionaPedido($pedidonull);
  5907.                 } else {
  5908.                     return new JsonResponse([], 202);
  5909.                 }
  5910.                 
  5911.             } else {
  5912.                 $pedido->setStatus('aceito');
  5913.                 $pedido->setLastUpdateStatus(new \DateTime('now'));
  5914.                 $this->criaRotaEAdicionaPedido($pedidonull);
  5915.             }
  5916.         //}
  5917.         if($this->getIsEntregadorAux()) {
  5918.             
  5919.             //$pedido->setAuxiliar($user->getEmail());
  5920.             $usuarioSelecionado $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
  5921.             
  5922.             // if(!$data->atendente){
  5923.             //     $usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$user->getEmail()]);
  5924.             // } else {
  5925.             //     $usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
  5926.             // }
  5927.             
  5928.             if(!$usuarioSelecionado instanceof User){
  5929.                 return new JsonResponse([], 400);
  5930.             }
  5931.             
  5932.             $pedido->setColaboradorUser($usuarioSelecionado);
  5933.                 
  5934.         } else {
  5935.             if($data->isAuxiliar==1){
  5936.                 if(!$data->atendente){
  5937.                     $pedido->setAuxiliar($user->getEmail());
  5938.                 } else {
  5939.                    $pedido->setAuxiliar($data->atendente); 
  5940.                 }
  5941.                 
  5942.                 //$usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
  5943.             } else {
  5944.                 
  5945.                 if(!$data->atendente){
  5946.                   $usuarioSelecionado $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$user->getEmail()]);
  5947.                 } else {
  5948.                    $usuarioSelecionado $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]); 
  5949.                 }
  5950.         
  5951.                 if(!$usuarioSelecionado instanceof User){
  5952.                     return new JsonResponse([], 400);
  5953.                 }
  5954.                 
  5955.                 $pedido->setColaboradorUser($usuarioSelecionado);
  5956.             }
  5957.         }
  5958.         
  5959.         $pedido->setAceitoAt(new \DateTime());
  5960.         
  5961.          // Faz um lancamentos
  5962.         if($pedido->getMeioEntrega()=='Viagem pela Pollo Móveis') {
  5963.             
  5964.             if($data->isAuxiliar==1){
  5965.                 
  5966.                 if(!$data->atendente){
  5967.                     $usuarioAuxiliar $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$user->getEmail()]);
  5968.                 } else {
  5969.                    $usuarioAuxiliar $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]); 
  5970.                 }
  5971.                 if($usuarioAuxiliar instanceof User) {
  5972.                     
  5973.                     // $descricao = "Viagem pela Pollo Móveis - Pedido {$pedido->getPedido()} - Endereço: {$pedido->getEndereco()}";
  5974.                     
  5975.                     // $lancamentoNovo = $this->getDoctrine()->getRepository(LancamentoFinanceiroColaborador::class)
  5976.                     // ->findOneBy(['colaborador'=>$usuarioAuxiliar, 'descricao'=>$descricao]);
  5977.                     
  5978.                     // if(!$lancamentoNovo instanceof LancamentoFinanceiroColaborador){
  5979.                     //     $lancamento = new LancamentoFinanceiroColaborador();
  5980.                     //     $lancamento->setColaborador($usuarioAuxiliar);
  5981.                     //     $lancamento->setTipo('credito');
  5982.                     //     $lancamento->setValor(120);
  5983.                     //     $lancamento->setData(new \DateTime());
  5984.                     //     $lancamento
  5985.                     //     ->setDescricao($descricao);
  5986.                     //     $this->getDoctrine()->getManager()->persist($lancamento);
  5987.                     //     $this->getDoctrine()->getManager()->flush();
  5988.                     // }
  5989.                     
  5990.                 }
  5991.                 
  5992.             } else {
  5993.                 
  5994.                 $descricao "Viagem pela Pollo Móveis - Pedido {$pedido->getPedido()} - Endereço: {$pedido->getEndereco()}";
  5995.                 
  5996.                 // $lancamentoNovo = $this->getDoctrine()->getRepository(LancamentoFinanceiroColaborador::class)
  5997.                 // ->findOneBy(['colaborador'=>$usuarioAuxiliar, 'descricao'=>$descricao]);
  5998.                 
  5999.                 // if(!$lancamentoNovo instanceof LancamentoFinanceiroColaborador){
  6000.                 //     $lancamento = new LancamentoFinanceiroColaborador();
  6001.                 //     $lancamento->setColaborador($usuarioSelecionado);
  6002.                 //     $lancamento->setTipo('credito');
  6003.                 //     $lancamento->setValor(220);
  6004.                 //     $lancamento->setData(new \DateTime());
  6005.                 //     $lancamento
  6006.                 //     ->setDescricao($descricao);
  6007.                 //     $this->getDoctrine()->getManager()->persist($lancamento);
  6008.                 //     $this->getDoctrine()->getManager()->flush();
  6009.                 // }
  6010.             }
  6011.         
  6012.         }
  6013.         
  6014.         $pedido->setLastUpdateStatus(new \DateTime('now'));
  6015.         $this->getDoctrine()->getManager()->flush();
  6016.         $todosPedios = [];
  6017.         
  6018.         if($this->getUser() instanceof User){
  6019.             $todosPedios $this->todosPedidosPorStatus();
  6020.         }
  6021.         
  6022.         return new JsonResponse($todosPedios200);
  6023.     
  6024.     }
  6025.     /**
  6026.      * @Route("/app-externo/informar-status", name="informmar_estatus", methods={"POST"})
  6027.      */
  6028.     public function entregarPedidos(Request $requestLogAcoesService $logAcoesServiceEntityManagerInterface $entityManager): Response
  6029.     {
  6030.         $data json_decode($request->getContent(), false);
  6031.         $pedido $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
  6032.         $origem $this->getStatusCorretoNome($pedido->getStatus());
  6033.         if(!$pedido instanceof EntregaPedido){
  6034.             return new JsonResponse($pedidosData400);
  6035.         }
  6036.         
  6037.         if($data->status == 'transito'){
  6038.             if($this->getIsEntregador()){
  6039.                 
  6040.                 $pedidosEmTransito $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['status'=>'transito''colaboradorUser'=>$this->getUser(), 'deletedAt'=>null]);
  6041.                 
  6042.                 if(count($pedidosEmTransito)>0){ // Tem algum pedido em transito
  6043.                     $pedidosEmTransitoPendentes = [];
  6044.                     foreach ($pedidosEmTransito as $pedido){
  6045.                         $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  6046.                         $pedidosEmTransitoPendentes[] = $numeroPedido;
  6047.                     }
  6048.                     return new JsonResponse(['status'=>400'pedidos'=>implode(', '$pedidosEmTransitoPendentes)], 200);
  6049.                 }
  6050.                 
  6051.             }
  6052.         }
  6053.         if($data->status == 'entregue'){
  6054.             if($pedido->getFotos()!='' && $pedido->getNotas()!=''){
  6055.                 $pedido->setStatus($data->status);
  6056.                 $pedido->setEntregarAt(new \DateTime());
  6057.                 
  6058.                 // Remove esse pedido das rotas
  6059.                 $this->removePedidoRota($pedido);
  6060.                 
  6061.             } else {
  6062.                 return new JsonResponse($pedidosData401);
  6063.             }
  6064.         } else {
  6065.             $pedido->setStatus($data->status);
  6066.         }
  6067.         
  6068.         if($data->status == 'aceito'){
  6069.             
  6070.             $pedidoAssistencia strpos($pedido->getPedido(), "Assistência");
  6071.         
  6072.             if(!$this->getIsAdmin() && $pedidoAssistencia!==false){
  6073.                 return new JsonResponse([], 201);
  6074.             }
  6075.             
  6076.             if($pedido->getMeioEntrega()=='Viagem pela Pollo Móveis') {
  6077.                 
  6078.                 // $descricao = "Viagem pela Pollo Móveis - Pedido {$pedido->getPedido()} - Endereço: {$pedido->getEndereco()}";
  6079.                 
  6080.                 // $lancamentoNovo = $this->getDoctrine()->getRepository(LancamentoFinanceiroColaborador::class)
  6081.                 // ->findOneBy(['colaborador'=>$this->getUser(), 'descricao'=>$descricao]);
  6082.                 
  6083.                 // if(!$lancamentoNovo instanceof LancamentoFinanceiroColaborador){
  6084.                     
  6085.                 //     $lancamento = new LancamentoFinanceiroColaborador();
  6086.                 //     $lancamento->setColaborador($this->getUser());
  6087.                 //     $lancamento->setTipo('credito');
  6088.                 //     $lancamento->setValor(220);
  6089.                 //     $lancamento->setData(new \DateTime());
  6090.                 //     $lancamento->setDescricao($descricao);
  6091.                     
  6092.                 //     $this->getDoctrine()->getManager()->persist($lancamento);
  6093.                 //     $this->getDoctrine()->getManager()->flush();
  6094.                 // }
  6095.             }
  6096.             $pedido->setColaboradorUser($this->getUser());
  6097.             $pedido->setAceitoAt(new \DateTime());
  6098.         }
  6099.         
  6100.         if($data->status == 'baixado'){
  6101.             $pedido->setBaixadoAt(new \DateTime());
  6102.         }
  6103.         
  6104.         $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  6105.         $tipoPedido = ($pedido->getPedido()!='') ? '' ' - NF';
  6106.         
  6107.         if($data->status == 'transito'){
  6108.             
  6109.             if($this->getIsEntregadorAux()) {
  6110.                 
  6111.                 $pedido->setAuxiliar($this->getUser()->getEmail());
  6112.                 
  6113.             } else {
  6114.                 
  6115.                 $user $this->getUser();
  6116.                 if ($user) {
  6117.                     if($pedido->getColaboradorUser()->getId()!=$this->getUser()->getId() && !$this->getIsAdmin()){
  6118.                         return new JsonResponse([], 400);
  6119.                     }
  6120.                 }
  6121.             }
  6122.             
  6123.             $pedido->setDataInicioEntrega(new \DateTime('now'));
  6124.             
  6125.             $motorista      $pedido->getColaboradorUser()->getNome();
  6126.             $motoristaTel   $pedido->getColaboradorUser()->getTelefone();
  6127.             
  6128.             $messageBody "Seu Pedido Nº $numeroPedido ou Assistência entrou na *Rota de Entrega/Transportadora*.\n\nCaso queira saber o horário mais próximo da chegada, favor entrar em contato com o entregador.\n\n*".$motorista."* - " .$motoristaTel;
  6129.             $messageImagemBody 'entrega.jpeg?v=12';
  6130.             $messageImagemBody 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/' $messageImagemBody '?v='.time();
  6131.             
  6132.             $type 'img';
  6133.             
  6134.             // $this->sendMensagemViaWhatsapp($type, $pedido->getTelefone(), $messageBody, $messageImagemBody, null, null);
  6135.             
  6136.             $numeroTelefone $pedido->getTelefone();
  6137.             $telefones explode('|'$numeroTelefone);
  6138.             
  6139.             if(count($telefones)>1){
  6140.                 
  6141.                 if($telefones[0]!=$telefones[1]){
  6142.                     
  6143.                     $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  6144.                     $this->sendMensagemViaWhatsapp($type$telefones[1], $messageBody$messageImagemBodynullnull);     
  6145.                     
  6146.                 } else {
  6147.                     $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  6148.                 }
  6149.                 
  6150.             } else {
  6151.                 $this->sendMensagemViaWhatsapp($type$telefones[0], $messageBody$messageImagemBodynullnull);     
  6152.             }
  6153.         }
  6154.         
  6155.         $pedido->setLastUpdateStatus(new \DateTime('now'));
  6156.         $this->getDoctrine()->getManager()->flush();
  6157.         
  6158.         $status $this->getStatusCorretoNome($data->status);
  6159.         // $numeroPedido .= $tipoPedido;
  6160.         // $logAcoesService
  6161.         // ->registraAcao(
  6162.         //     $entityManager,
  6163.         //     $this->getUser(),
  6164.         //     'Mudança de status para: ' . $status,
  6165.         //     $numeroPedido,
  6166.         //     'O card veio de: ' . $origem
  6167.         // );
  6168.         
  6169.         $todosPedidos = [];
  6170.         if($this->getUser() instanceof User) {
  6171.             return new JsonResponse($this->todosPedidosPorStatus(), 200);
  6172.         }
  6173.         
  6174.         return new JsonResponse($todosPedidos200);
  6175.     }
  6176.     
  6177.     private function removePedidoRota($pedido) {
  6178.         
  6179.         if($pedido->getRoute() instanceof EntregaRoute){
  6180.             
  6181.             $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
  6182.             
  6183.             // Converte a string em um array
  6184.             $array explode(','$pedido->getRoute()->getPedidos());
  6185.             
  6186.             // Procura o índice do pedido que você quer remover
  6187.             $indice array_search($numeroPedido$array);
  6188.             
  6189.             // Se o pedido for encontrado, remove do array
  6190.             if ($indice !== false) {
  6191.                 unset($array[$indice]);
  6192.             }
  6193.             
  6194.             // Reconverte o array de volta para uma string
  6195.             $stringAtualizada implode(','$array);
  6196.             
  6197.             $pedido->getRoute()->setPedidos($stringAtualizada);
  6198.             
  6199.             $this->getDoctrine()->getManager()->flush();
  6200.         }
  6201.         
  6202.         
  6203.         
  6204.         // $rotas = $this->getDoctrine()->getRepository(EntregaRoute::class)->findByPedido($numeroPedido);
  6205.         // if(count($rotas)>0){
  6206.         //     foreach ($rotas as $rota){
  6207.         //         // Converte a string em um array
  6208.         //         $array = explode(',', $rota->getPedidos());
  6209.                 
  6210.         //         // Procura o índice do pedido que você quer remover
  6211.         //         $indice = array_search($numeroPedido, $array);
  6212.                 
  6213.         //         // Se o pedido for encontrado, remove do array
  6214.         //         if ($indice !== false) {
  6215.         //             unset($array[$indice]);
  6216.         //         }
  6217.                 
  6218.         //         // Reconverte o array de volta para uma string
  6219.         //         $stringAtualizada = implode(',', $array);
  6220.                 
  6221.         //         $rota->setPedidos($stringAtualizada);
  6222.         //     }
  6223.         // }
  6224.         
  6225.     }
  6226.     
  6227.     /**
  6228.      * @Route("/app-externo/lista-pedidos", name="lista_app_externo", methods={"POST"})
  6229.      */
  6230.     public function listaPedidos(Request $request): Response
  6231.     {
  6232.         $data json_decode($request->getContent(), false);
  6233.         return new JsonResponse($this->todosPedidosPorStatus($data->pedidoFiltrado$data->field), 200);
  6234.     }
  6235.     
  6236.     private function getPedidos($status$busca=false) {
  6237.         $user $this->getUser();
  6238.         $pedidosData = [];
  6239.         $hoje = new \DateTime();
  6240.         
  6241.         $user $this->getUser();
  6242.         
  6243.         if($status!='pendente' && $status!='recebido') {
  6244.             
  6245.             if($status=='baixado') {
  6246.                 
  6247.                 if(!$busca){
  6248.                     $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['deletedAt'=>null'status'=>$status], array('updatedAt' => 'DESC'), 100);
  6249.                 } else {
  6250.                     $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['deletedAt'=>null'status'=>$status], array('updatedAt' => 'DESC'));
  6251.                 }
  6252.                 
  6253.             } else {
  6254.                 
  6255.                 if($status!='pendente') {
  6256.                     
  6257.                     // Veriicar se é super admin
  6258.                     if($this->getIsAdmin() || $this->getIsVendedor()) {
  6259.                         $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null'status'=>$status], array('updatedAt' => 'DESC'));
  6260.                     } else {
  6261.                         
  6262.                         if($this->getIsEntregadorAux()){
  6263.                             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null'deletedAt'=>null'status'=>$status'auxiliar'=>$user->getEmail()], array('updatedAt' => 'DESC'));
  6264.                         } else {
  6265.                             // $pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'status'=>$status], array('id' => 'DESC'));
  6266.                             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null'status'=>$status'colaboradorUser'=>$user], array('updatedAt' => 'DESC'));
  6267.                         }
  6268.     
  6269.                     }
  6270.                     
  6271.                 } else {
  6272.                     
  6273.                     // Veriicar se é super admin
  6274.                     if($this->getIsAdmin() || $this->getIsVendedor()) {
  6275.                         $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null'status'=>$status], array('updatedAt' => 'DESC'));
  6276.                     } else {
  6277.                         
  6278.                         if($this->getIsEntregadorAux()){
  6279.                             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null'deletedAt'=>null'status'=>$status'auxiliar'=>$user->getEmail()], array('updatedAt' => 'DESC'));
  6280.                         } else {
  6281.                             // $pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'status'=>$status], array('id' => 'DESC'));
  6282.                             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null'status'=>$status'colaboradorUser'=>$user], array('updatedAt' => 'DESC'));
  6283.                         }
  6284.     
  6285.                     }
  6286.                     
  6287.                 }
  6288.             }
  6289.             
  6290.         } else {
  6291.             // Se for pendente todos podem ver
  6292.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null'deletedAt'=>null'status'=>$status], array('updatedAt' => 'DESC'));
  6293.         }
  6294.         
  6295.         foreach ($pedidos as $pedido) {
  6296.             
  6297.             
  6298.             
  6299.             // $obsVendedorStr = '';
  6300.             
  6301.             // $obsVendedor = explode('-', $pedido->getObsVendedor());
  6302.             
  6303.             // if(count($obsVendedor)>0) {
  6304.                 
  6305.             //     foreach ($obsVendedor as $obsVendedorStrItem) {
  6306.             //         $obsVendedorStr .= '<div class="blink_me badge-pollo">'.strip_tags($obsVendedorStrItem).'</div>';
  6307.             //     }
  6308.             
  6309.             // } else {
  6310.             //     $obsVendedorStr = $obsVendedor;
  6311.             // }
  6312.             
  6313.             // Pular pedidos deletados
  6314.             if($pedido->getDeletedAt()!=null && $pedido->getDeletedAt()!='') {
  6315.                continue;
  6316.             }
  6317.             
  6318.             $pedidosData[] = $this->makeProdutoData($pedido);
  6319.         }
  6320.         
  6321.         return $pedidosData;
  6322.     }
  6323.     
  6324.     public function isDonoPedido($pedido) {
  6325.         
  6326.         if(!$pedido->getColaboradorUser()){
  6327.             return false;
  6328.         }
  6329.         
  6330.         if(!$this->getUser() instanceof User){
  6331.             return false;
  6332.         }
  6333.         
  6334.         // if(!$pedido->getColaboradorUser() instanceof User || 
  6335.         // !$this->getUser() instanceof User || 
  6336.         // !$pedido->getAuxiliar()==$this->getUser() instanceof User){
  6337.         //     return false;
  6338.         // }
  6339.         
  6340.         return ($pedido->getColaboradorUser()->getId() == $this->getUser()->getId() || $pedido->getAuxiliar()==$this->getUser()->getEmail());
  6341.     }
  6342.     
  6343.     private function getPedido($numero$client$tipoPedido='pedido'$pedidoMake=null) {
  6344.         
  6345.         $response $client->request(
  6346.             'GET',
  6347.             SincronizacaoController::URL_API_BLING '/pedido/'.$numero.'/json/',
  6348.             [
  6349.                 'query' => [
  6350.                     'apikey' => SincronizacaoController::KEY_API_POLLO
  6351.                 ]
  6352.             ]
  6353.         );
  6354.         $statusCode $response->getStatusCode();
  6355.         $numeroNota '';
  6356.         $dados = [
  6357.             'telefone' =>'',
  6358.             'endereco' => '',
  6359.             'endereco_entrega' => '',
  6360.             'tipo'     => $tipoPedido,
  6361.             'numeroNf' => '',
  6362.             'numeroPedido' => $numero,
  6363.             'isUrgente' => 'Não',
  6364.             'assistencia' => 'Não',
  6365.             'contato' => ''
  6366.             'periodosEntrega' => '',
  6367.             'entregarHoje' => '',
  6368.             'vendedor' => '',
  6369.             'embalagem' => 'Desmontado',
  6370.             'exigeLadoBalcao' => false// Qual lado do balcão
  6371.             'cnpj' => '',
  6372.             'frete' =>'',
  6373.             'solicitarColeta' => '',
  6374.             'nomeTrasportadora' => '',
  6375.             'meioEntrega' => '',
  6376.             'esperarClientePagar' => 'Não',
  6377.             'cotarFrete' => '',
  6378.             'itens' => '',
  6379.             'dataAgendamentoEntrega' => ''
  6380.         ];
  6381.         if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
  6382.             $content $response->toArray();
  6383.             if(isset($content['retorno'])){
  6384.                 if(isset($content['retorno']['pedidos'])){
  6385.                     if(count($content['retorno']['pedidos']) > 0) {
  6386.                         if(isset($content['retorno']['pedidos'][0])){
  6387.                             
  6388.                             $pedido $content['retorno']['pedidos'][0]['pedido'];
  6389.                             
  6390.                             if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'])){
  6391.                                 
  6392.                                 $dados['endereco'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'] . ',  ' 
  6393.                                                      $content['retorno']['pedidos'][0]['pedido']['cliente']['numero'] . ',  ' 
  6394.                                                      $content['retorno']['pedidos'][0]['pedido']['cliente']['complemento'] . ',  ' 
  6395.                                                      $content['retorno']['pedidos'][0]['pedido']['cliente']['bairro'] . ',  ' 
  6396.                                                      $content['retorno']['pedidos'][0]['pedido']['cliente']['cidade'] . '/' 
  6397.                                                      $content['retorno']['pedidos'][0]['pedido']['cliente']['uf'] . ',  ' 
  6398.                                                      $content['retorno']['pedidos'][0]['pedido']['cliente']['cep'] . ',  ';
  6399.                                     
  6400.                             }
  6401.                             $dados['contato'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['nome'];
  6402.                             
  6403.                             $telefones = [];
  6404.                             if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['celular'])){
  6405.                                 if($content['retorno']['pedidos'][0]['pedido']['cliente']['celular']!=""){
  6406.                                     $telefone $content['retorno']['pedidos'][0]['pedido']['cliente']['celular'];
  6407.                                     $telefone '55'.$telefone;
  6408.                                     $telefones[] = preg_replace('/\D/'''$telefone);
  6409.                                     
  6410.                                 }
  6411.                             }
  6412.                             
  6413.                             if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['fone'])){
  6414.                                 if($content['retorno']['pedidos'][0]['pedido']['cliente']['fone']!=""){
  6415.                                     $telefone $content['retorno']['pedidos'][0]['pedido']['cliente']['fone'];
  6416.                                     $telefone '55'.$telefone;
  6417.                                     $telefones[] = preg_replace('/\D/'''$telefone);
  6418.                                 }
  6419.                             }
  6420.                             
  6421.                             $dados['telefone'] = implode('|'$telefones);
  6422.                             
  6423.                             if(isset($content['retorno']['pedidos'][0]['pedido']['nota'])){
  6424.                                 $dados['numeroNf'] = intval($content['retorno']['pedidos'][0]['pedido']['nota']['numero']);
  6425.                             }
  6426.                             
  6427.                             $dados['vendedor'] =  $content['retorno']['pedidos'][0]['pedido']['vendedor'];
  6428.                             
  6429.                             $dados['cnpj'] = '';
  6430.                             $dados['totalvenda'] = '';
  6431.                             $dados['itens'] = [];
  6432.                             
  6433.                             if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['cnpj'])){
  6434.                                 $dados['cnpj'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['cnpj'];
  6435.                             }
  6436.                             
  6437.                             $dataPedido = \DateTime::createFromFormat('Y-m-d'$content['retorno']['pedidos'][0]['pedido']['data']);
  6438.                             $dados['data'] = $dataPedido->format('d/m/Y');
  6439.                             
  6440.                             $totalItens 0;
  6441.                             $totalItensTotal 0;
  6442.                             $valorSubTotal 0;
  6443.                             $descontosItens 0;
  6444.                             if(!empty($content['retorno']['pedidos'][0]['pedido']['itens'])){
  6445.                                 foreach ($content['retorno']['pedidos'][0]['pedido']['itens'] as $item) {
  6446.                                     
  6447.                                     if(in_array($item['item']['codigo'], $this->skusDebalcao())){
  6448.                                         $dados['exigeLadoBalcao'] = true;
  6449.                                     }
  6450.                                     
  6451.                                     $totalItens++;
  6452.                                     $valorTotal $item['item']['quantidade'] * $item['item']['valorunidade'];
  6453.                                     $valorSubTotal += $valorTotal;
  6454.                                     $totalItensTotal += $item['item']['quantidade'];
  6455.                                     $descontosItens += $item['item']['descontoItem'];
  6456.                                     
  6457.                                     $img '';
  6458.                                     $pathFile '/www/wwwroot/gestor.moveispollo.com.br/public/uploads/produtos/' $item['item']['codigo'] . '.jpg';
  6459.                                     
  6460.                                     if(file_exists($pathFile)){
  6461.                                         $img 'https://polo.srvtmp.com.br/uploads/produtos/' $item['item']['codigo'] . '.jpg';
  6462.                                     } else {
  6463.                                         
  6464.                                         $produtoBling $this->getProduto(SincronizacaoController::KEY_API_POLLO
  6465.                                             $item['item']['codigo'], $client$xml=false);
  6466.                                             
  6467.                                         if(isset($produtoBling['retorno']['produtos'][0])) {
  6468.                                             if(isset($produtoBling['retorno']['produtos'][0]['produto']['imagem'][0])) {
  6469.                                                 $img $produtoBling['retorno']['produtos'][0]['produto']['imagem'][0]['link'];
  6470.                                                 $img str_ireplace('\\','',$img);
  6471.                                             }
  6472.                                         }
  6473.                                         
  6474.                                     }
  6475.                         
  6476.                                     $dados['itens'][] = [
  6477.                                         'codigo' => $item['item']['codigo'],
  6478.                                         'descricao' => $item['item']['descricao'],
  6479.                                         'un' => $item['item']['un'],
  6480.                                         'quantidade' => abs($item['item']['quantidade']),
  6481.                                         'valorunidade' => number_format($item['item']['valorunidade'], 2',''.'),
  6482.                                         'valorTotal' => number_format($valorTotal2',''.'),
  6483.                                         'img' => $img,
  6484.                                         'estruturas' => $this->getEstruturas($item['item']['codigo']) // Primeiro nivel
  6485.                                     ];
  6486.                                 }
  6487.                             }
  6488.                             
  6489.                             $dados['parcelas'] = [];
  6490.                             if(!empty($content['retorno']['pedidos'][0]['pedido']['parcelas'])) {
  6491.                                 foreach ($content['retorno']['pedidos'][0]['pedido']['parcelas'] as $parcela) {
  6492.                                     
  6493.                                     
  6494.                                     $dataVencimento = \DateTime::createFromFormat('Y-m-d'$parcela['parcela']['dataVencimento']);
  6495.                                     
  6496.                                     $dados['parcelas'][] = [
  6497.                                         'valor' => number_format($parcela['parcela']['valor'], 2',''.'),
  6498.                                         'dias' => '0',
  6499.                                         'dataVencimento' => $dataVencimento->format('d/m/Y'),
  6500.                                         'formaPagamento' => $parcela['parcela']['forma_pagamento']['descricao'],
  6501.                                         'obs' => $parcela['parcela']['obs']
  6502.                                     ];
  6503.                                 }
  6504.                             }
  6505.             
  6506.                             $dados['numero_itens'] = $totalItens;
  6507.                             $dados['numero_itens_total'] = $totalItensTotal;
  6508.                             $dados['descontos'] = number_format($descontosItens2',''.');
  6509.                             $dados['valorTotalPedido'] = number_format($valorSubTotal2',''.');
  6510.                             $dados['valorTotalComDesconto'] = number_format($content['retorno']['pedidos'][0]['pedido']['totalvenda'], 2',''.');
  6511.                             
  6512.                             $dados['obs'] = $content['retorno']['pedidos'][0]['pedido']['observacoes'];
  6513.                             $dados['frete'] = (isset($content['retorno']['pedidos'][0]['pedido']['valorfrete'])) ? $content['retorno']['pedidos'][0]['pedido']['valorfrete'] : '';
  6514.                             
  6515.                             $dados['descontoGeral'] = $content['retorno']['pedidos'][0]['pedido']['desconto'];
  6516.                             
  6517.                             $pedidoEntrega $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido' => $numero]);
  6518.                             $dados['showMaisPedidos'] = false;
  6519.                             
  6520.                             $dados['estruturas'] = $this->agrupaEstruturas($dados['itens']);
  6521.                             
  6522.                             if($pedidoEntrega instanceof EntregaPedido){
  6523.                                 if($pedidoMake instanceof EntregaPedido){
  6524.                                     $dados['mais_info'] = $this->makeProdutoData($pedidoMaketrue);
  6525.                                 } else {
  6526.                                     $dados['mais_info'] = $this->makeProdutoData($pedidoEntregatrue);
  6527.                                 }
  6528.                                 
  6529.                                 $dados['showMaisPedidos'] = true;
  6530.                             }
  6531.                             
  6532.                             if(!empty($content['retorno']['pedidos'][0]['pedido']['transporte'])){
  6533.                                 
  6534.                                 if(!empty($content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega'])){    
  6535.                                     
  6536.                                         $dados['endereco_entrega'] = 
  6537.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['endereco'] . ',  ' 
  6538.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['numero'] . ',  ' 
  6539.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['complemento'] . ',  ' .
  6540.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['bairro'] . ',  ' 
  6541.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['cidade'] . '/' 
  6542.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['uf'] . ',  ' 
  6543.                                             $content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['cep'] . ',  ';
  6544.                                 }
  6545.                                 
  6546.                             }
  6547.                             
  6548.                             //print_r($dados['itens']); exit;
  6549.                             
  6550.                             return $dados;
  6551.                             
  6552.                         }
  6553.                     }
  6554.                 }
  6555.             }
  6556.         } else {
  6557.             exit('Erro em bucar pedido: ' $numero);
  6558.         }
  6559.         return false;
  6560.     }
  6561.     
  6562.     public function agrupaEstruturas($itens) {
  6563.         
  6564.         $estruturas = [];
  6565.         
  6566.         foreach ($itens as $item) {
  6567.             if(isset($item['estruturas']) && !empty($item['estruturas'])){
  6568.             
  6569.                 foreach ($item['estruturas'] as $estrutura) {
  6570.                     
  6571.                     $produtoBling $this->getDoctrine()->getRepository(ProdutoBling::class)->findOneBy(['codigo' => $estrutura->codigo]);
  6572.                     if(!$produtoBling instanceof ProdutoBling){
  6573.                         continue;
  6574.                     }
  6575.                     
  6576.                     $isSimples false;
  6577.                     if($produtoBling->getIsSimples()){
  6578.                         $isSimples $produtoBling->getIsSimples();
  6579.                     }
  6580.                     
  6581.                     $quantidade $estrutura->quantidade $item['quantidade'];
  6582.                     
  6583.                     $estruturas[] = [
  6584.                         'nome' => $estrutura->nome,
  6585.                         'codigo' => $estrutura->codigo,
  6586.                         'quantidade' => $quantidade,
  6587.                         'isSimples' => $isSimples
  6588.                     ];
  6589.                 }
  6590.             }
  6591.         }
  6592.         $itensAgrupados = array();
  6593.         
  6594.         // Iterar sobre os itens originais
  6595.         foreach ($estruturas as $item) {
  6596.             
  6597.             $codigo $item["codigo"];
  6598.             $quantidade $item["quantidade"];
  6599.             
  6600.             // Se o código já existir no array $itensAgrupados, adicione a quantidade
  6601.             if (isset($itensAgrupados[$codigo])) {
  6602.                 $itensAgrupados[$codigo]["quantidade"] += $quantidade;
  6603.             } else {
  6604.                 // Se não, crie uma nova entrada no array
  6605.                 $itensAgrupados[$codigo] = array(
  6606.                     "nome" => $item["nome"],
  6607.                     "codigo" => $codigo,
  6608.                     "quantidade" => $quantidade,
  6609.                     'isSimples' => $item["isSimples"]
  6610.                 );
  6611.             }
  6612.         }
  6613.         
  6614.         // Resultado final com itens agrupados e quantidades somadas
  6615.         $resultadoFinal array_values($itensAgrupados);
  6616.         return $resultadoFinal;
  6617.     }
  6618.     
  6619.     public function getEstruturas($codigo){
  6620.         
  6621.         $produtoBling $this->getDoctrine()->getRepository(ProdutoBling::class)->findOneBy(['codigo' => $codigo]);
  6622.         
  6623.         if($produtoBling instanceof ProdutoBling) {
  6624.             $estruturas json_decode($produtoBling->getEstrutura());
  6625.             if(!empty($produtoBling->getEstrutura())){
  6626.                 
  6627.                 foreach ($estruturas as $estrutura){ // Pego para cada item uma estrutura dentro
  6628.                     $subEstruturas $this->getSubEstruturas($estrutura->codigo);
  6629.                     if(!empty($subEstruturas)){
  6630.                         foreach ($subEstruturas as $subEstrutura){
  6631.                             $estruturas[] = $subEstrutura;
  6632.                         }
  6633.                     }
  6634.                 }
  6635.                 
  6636.                 return (count($estruturas)>0) ? $estruturas '';
  6637.             }
  6638.             return '';
  6639.         }
  6640.         
  6641.         return '';
  6642.     }
  6643.     
  6644.     public function getSubEstruturas($codigo) { 
  6645.         
  6646.         $produtoBling $this->getDoctrine()->getRepository(ProdutoBling::class)->findOneBy(['codigo' => $codigo]);
  6647.         
  6648.         if($produtoBling instanceof ProdutoBling) {
  6649.             $estruturas json_decode($produtoBling->getEstrutura());
  6650.             if(!empty($produtoBling->getEstrutura())){
  6651.                 return (count($estruturas)>0) ? $estruturas '';
  6652.             }
  6653.             return '';
  6654.         }
  6655.         
  6656.         return '';
  6657.     }
  6658.     
  6659.     private function getNotaFiscal($numero$client$tipoPedido) {
  6660.         
  6661.         $response $client->request(
  6662.             'GET',
  6663.             SincronizacaoController::URL_API_BLING '/notafiscal/'.$numero.'/1/json/',
  6664.             [
  6665.                 'query' => [
  6666.                     'apikey' => SincronizacaoController::KEY_API_POLLO
  6667.                 ]
  6668.             ]
  6669.         );
  6670.         
  6671.         $dados = [
  6672.             'telefone' =>'',
  6673.             'endereco' => '',
  6674.             'tipo'     => $tipoPedido,
  6675.             'numeroNf' => $numero,
  6676.             'numeroPedido' => '',
  6677.             'isUrgente' => 'Não',
  6678.             'assistencia' => 'Não',
  6679.             'contato' => ''
  6680.             'periodosEntrega' => '',
  6681.             'entregarHoje' => '',
  6682.             'vendedor' => '',
  6683.             'embalagem' => 'Desmontado',
  6684.             'exigeLadoBalcao' => false// Qual lado do balcão
  6685.             'cnpj' => '',
  6686.             'solicitarColeta' => '',
  6687.             'nomeTrasportadora' => '',
  6688.             'meioEntrega' => '',
  6689.             'cotarFrete' => '',
  6690.             'esperarClientePagar' => 'Não',
  6691.             'dataAgendamentoEntrega' => ''
  6692.         ];
  6693.         $statusCode $response->getStatusCode();
  6694.         if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
  6695.             $content $response->toArray();
  6696.             if(isset($content['retorno'])){
  6697.                 if(isset($content['retorno']['notasfiscais'])){
  6698.                     if(count($content['retorno']['notasfiscais']) > 0) {
  6699.                             $notafiscal $content['retorno']['notasfiscais'][0]['notafiscal'];
  6700.                             $data explode(' ',$notafiscal['dataEmissao']);
  6701.                             $data explode('-',$data[0]);
  6702.                             
  6703.                             $keyNota $notafiscal['chaveAcesso'];
  6704.                             //$url = 'https://www.bling.com.br/relatorios/nfe.xml.php?s&chaveAcesso=' . $keyNota;
  6705.                             $url $notafiscal['xml'];
  6706.                             $url str_replace("\\""/"$url);
  6707.                             $xmlNota simplexml_load_file($url);
  6708.                             //$xmlNota->NFe->infNFe->cobr->fat->vLiq
  6709.                             
  6710.                             $trasportadora 'A retirar';
  6711.                             
  6712.                             if(isset($xmlNota->NFe->infNFe->transp)){
  6713.                                 if(isset($xmlNota->NFe->infNFe->transp->transporta)){
  6714.                                     $trasportadora $xmlNota->NFe->infNFe->transp->transporta->xNome;
  6715.                                 }
  6716.                             }
  6717.                             
  6718.                             // $telefone = '';
  6719.                             
  6720.                             // if(isset($notafiscal['cliente']['celular'])){
  6721.                             //     if($notafiscal['cliente']['celular']!=""){
  6722.                             //         $telefone = $notafiscal['cliente']['celular'];
  6723.                             //     }
  6724.                             // } else if(isset($notafiscal['cliente']['fone'])){
  6725.                             //     if($notafiscal['cliente']['fone']!=""){
  6726.                             //         $telefone = $notafiscal['cliente']['fone'];
  6727.                             //     }
  6728.                             // }
  6729.                             
  6730.                             $telefones = [];
  6731.                             if(isset($notafiscal['cliente']['celular'])){
  6732.                                 if($notafiscal['cliente']['celular']!=""){
  6733.                                     $telefone $notafiscal['cliente']['celular'];
  6734.                                     $telefone '55'.$telefone;
  6735.                                     $telefones[] = preg_replace('/\D/'''$telefone);
  6736.                                     
  6737.                                 }
  6738.                             }
  6739.                             
  6740.                             if(isset($notafiscal['cliente']['celular'])){
  6741.                                 if($notafiscal['cliente']['celular']!=""){
  6742.                                     $telefone $notafiscal['cliente']['celular'];
  6743.                                     $telefone '55'.$telefone;
  6744.                                     $telefones[] = preg_replace('/\D/'''$telefone);
  6745.                                 }
  6746.                             }
  6747.                             
  6748.                             $dados['telefone'] = implode('|'$telefones);
  6749.                             
  6750.                             
  6751.                             if(isset($notafiscal['cliente']['nome'])){
  6752.                                 $dados['contato'] = $notafiscal['cliente']['nome'];    
  6753.                             }
  6754.                             if(!empty($notafiscal['cliente'])){
  6755.                                 
  6756.                                     $dados['endereco'] = $notafiscal['cliente']['endereco'] . ',  ' 
  6757.                                                          $notafiscal['cliente']['numero'] . ',  ' 
  6758.                                                          $notafiscal['cliente']['complemento'] . ',  ' 
  6759.                                                          $notafiscal['cliente']['bairro'] . ',  ' 
  6760.                                                          $notafiscal['cliente']['cidade'] . '/' 
  6761.                                                          $notafiscal['cliente']['uf'] . ',  ' 
  6762.                                                          $notafiscal['cliente']['cep'] . ',  ';
  6763.                             }
  6764.                             
  6765.                             $dados['vendedor'] =  $notafiscal['vendedor'];
  6766.                             
  6767.                             $dados['cnpj'] = '';
  6768.                             
  6769.                             if(isset($notafiscal['cliente']['cnpj'])){
  6770.                                 $dados['cnpj'] = $notafiscal['cliente']['cnpj'];
  6771.                             }
  6772.                             
  6773.                             return $dados;
  6774.                             
  6775.                             // return [
  6776.                             //     'quantidade' => $volume,
  6777.                             //     'emissao' => $data[2] . '/' . $data[1] . '/' . $data[0],
  6778.                             //     'pedido' => $numero,
  6779.                             //     'cliente' => $notafiscal['cliente']['nome'],
  6780.                             //     'telefone' => $telefone,
  6781.                             //     'tipo' => 'nf',
  6782.                             //     'transportadora' => $trasportadora
  6783.                             // ];
  6784.                             
  6785.                     }
  6786.                 }
  6787.             }
  6788.         }
  6789.         
  6790.         return false;
  6791.     }
  6792.     
  6793.     private function isAdmin() {
  6794.        return ($this->getUser()->getEmail()=='bruno@moveispollo.com.br');
  6795.     }
  6796.     
  6797.     private function getDadosCliente($pedido$client){
  6798.         if(empty($pedido)) {
  6799.             return '';
  6800.         }
  6801.         
  6802.         $dados = [
  6803.             'telefone' =>'',
  6804.             'endereco' => '',
  6805.             'produtos' => []
  6806.         ];
  6807.         $numero '';
  6808.         $lojas = [
  6809.             ['nome' => 'polo',     'api' => SincronizacaoController::KEY_API_POLLO]
  6810.         ];
  6811.         foreach ($lojas as $loja) {
  6812.             $response $client->request(
  6813.                 'GET',
  6814.                 SincronizacaoController::URL_API_BLING '/pedido/'.$pedido.'/json/',
  6815.                 [
  6816.                     'query' => [
  6817.                         'apikey'   => $loja['api']
  6818.                     ]
  6819.                 ]
  6820.             );
  6821.             $statusCode $response->getStatusCode();
  6822.             
  6823.             if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
  6824.                 $content $response->toArray();
  6825.                 if(isset($content['retorno'])){
  6826.                     if(isset($content['retorno']['pedidos'])){
  6827.                         if(count($content['retorno']['pedidos']) > 0) {
  6828.                             if(isset($content['retorno']['pedidos'][0])){
  6829.                                 
  6830.                                 
  6831.                                 if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'])){
  6832.                                     $dados['endereco'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'] . ',  ' 
  6833.                                                          $content['retorno']['pedidos'][0]['pedido']['cliente']['numero'] . ',  ' 
  6834.                                                          $content['retorno']['pedidos'][0]['pedido']['cliente']['complemento'] . ',  ' 
  6835.                                                          $content['retorno']['pedidos'][0]['pedido']['cliente']['bairro'] . ',  ' 
  6836.                                                          $content['retorno']['pedidos'][0]['pedido']['cliente']['cidade'] . '/' 
  6837.                                                          $content['retorno']['pedidos'][0]['pedido']['cliente']['uf'] . ',  ' 
  6838.                                                          $content['retorno']['pedidos'][0]['pedido']['cliente']['cep'] . ',  ';
  6839.                                 }
  6840.                                 
  6841.                                 if(!empty($content['retorno']['pedidos'][0]['pedido']['itens'])){
  6842.                                     
  6843.                                     if(count($content['retorno']['pedidos'][0]['pedido']['itens'])>0){
  6844.                                         
  6845.                                         $produtos '';
  6846.                                         $totalProdutos 0;
  6847.                                         
  6848.                                         foreach ($content['retorno']['pedidos'][0]['pedido']['itens'] as $item){
  6849.                                             $quantidade $item['item']['quantidade'];
  6850.                                             $valorTotal $item['item']['valorunidade'] * $quantidade;
  6851.                                             $produtos .= "*Qtd:* " round($item['item']['quantidade']) . " - " $item['item']['descricao'] . " - R$ " 
  6852.                                             number_format($valorTotal2',''.') . "\n";
  6853.                                             $totalProdutos+=$valorTotal;
  6854.                                         }
  6855.                                         
  6856.                                         $valorComDesconto $content['retorno']['pedidos'][0]['pedido']['totalvenda'];
  6857.                                         $produtosStr "\n*Total Nota:* R$ " number_format($totalProdutos2',''.');
  6858.                                         $produtosStr .= "\n*Total c/ desconto:* R$ " number_format($valorComDesconto2',''.');
  6859.                                         
  6860.                                         $dados['produtos'] = $produtos $produtosStr;
  6861.                                     }
  6862.                                     
  6863.                                 }
  6864.                                 
  6865.                                 
  6866.                                 
  6867.                                 
  6868.                                 $telefones = [];
  6869.                                 if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['celular'])){
  6870.                                     if($content['retorno']['pedidos'][0]['pedido']['cliente']['celular']!=""){
  6871.                                         $telefone $content['retorno']['pedidos'][0]['pedido']['cliente']['celular'];
  6872.                                         $telefone '55'.$telefone;
  6873.                                         $telefones[] = preg_replace('/\D/'''$telefone);
  6874.                                         
  6875.                                     }
  6876.                                 }
  6877.                                 if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['fone'])){
  6878.                                     if($content['retorno']['pedidos'][0]['pedido']['cliente']['fone']!=""){
  6879.                                         $telefone $content['retorno']['pedidos'][0]['pedido']['cliente']['fone'];
  6880.                                         $telefone '55'.$telefone;
  6881.                                         $telefones[] = preg_replace('/\D/'''$telefone);
  6882.                                     }
  6883.                                 }
  6884.                                 
  6885.                                 $dados['telefone'] = implode('|'$telefones);
  6886.                                 
  6887.                                 // if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['fone'])){
  6888.                                 //     $dados['telefone'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['fone'];
  6889.                                 // }
  6890.                                 // if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['celular'])){
  6891.                                 //     $dados['telefone'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['celular'];
  6892.                                 // }
  6893.                                 
  6894.                                 $dados['vendedor'] =  $content['retorno']['pedidos'][0]['vendedor'];
  6895.                                 return $dados;
  6896.                                 break;
  6897.                             }
  6898.                         }
  6899.                     }
  6900.                 }
  6901.             }
  6902.         }
  6903.         return $dados;
  6904.     }
  6905.     
  6906.     private function todosPedidosPorStatus($pedidoFiltrado=''$fieldPassed='pedido'$busca=false$tipo='') {
  6907.         
  6908.         $pedidosDatabaixado = [];
  6909.         
  6910.         if($busca){
  6911.             
  6912.             $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilter($fieldPassed$pedidoFiltrado$tipo);
  6913.             
  6914.             foreach ($pedidos as $pedido) {
  6915.                 $pedidosDatabaixado[] = $this->makeProdutoData($pedido);
  6916.             }
  6917.             
  6918.             $mensagensChat $this->getAllMensagensChat();
  6919.             $temMensagemNaoLida false;
  6920.             foreach ($mensagensChat as $mensagemChat) {
  6921.                if(!$mensagemChat['isLida']){
  6922.                     $temMensagemNaoLida true;
  6923.                     break;
  6924.                }
  6925.             }
  6926.             
  6927.             return [
  6928.                 'pendentes'             => [], 
  6929.                 'aceitos'               => [], 
  6930.                 'entregues'             => [], 
  6931.                 'transito'              => [], 
  6932.                 'pendentes_admin'       => [], 
  6933.                 'baixados'              => $pedidosDatabaixado
  6934.                 'recebidos'             => [],
  6935.                 'cotacao'               => [],
  6936.                 'aguardando_pagamento'  => [],
  6937.                 'naoLidos'              => $this->getPedidosNaoLidos(),
  6938.                 'mensagensChat'         => $this->getAllMensagensChat(),
  6939.                 'temMensagemNaoLida'    => $temMensagemNaoLida
  6940.             ];
  6941.         }
  6942.         
  6943.         $pedidosDataPendentes               $this->getPedidos('pendente');
  6944.         $pedidosDataAceitos                 $this->getPedidos('aceito');
  6945.         $pedidosDataEntregues               $this->getPedidos('entregue');
  6946.         $pedidosDataTransito                $this->getPedidos('transito');
  6947.         $pedidosDataPendenteAdmin           $this->getPedidos('pendente_admin');
  6948.         $pedidosDatabaixado                 $this->getPedidos('baixado'$busca);
  6949.         $pedidosDataRecebido                $this->getPedidos('recebido');
  6950.         $pedidosDataCotacao                 $this->getPedidos('cotacao');
  6951.         $pedidosDataAguardandoPagamento     $this->getPedidos('aguardando_pagamento');
  6952.         
  6953.         if($pedidoFiltrado!=''){
  6954.             
  6955.             $jaExisteNaLista false;
  6956.             
  6957.             $field = ($fieldPassed=='sku') ? 'pedido' 'nota';
  6958.             foreach ($pedidosDataPendentes as $pedido) {
  6959.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6960.                     $jaExisteNaLista true;
  6961.                 }
  6962.             }
  6963.             
  6964.             foreach ($pedidosDataAceitos as $pedido) {
  6965.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6966.                     $jaExisteNaLista true;
  6967.                 }
  6968.             }
  6969.             
  6970.             foreach ($pedidosDataEntregues as $pedido) {
  6971.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6972.                     $jaExisteNaLista true;
  6973.                 }
  6974.             }
  6975.             
  6976.             foreach ($pedidosDataTransito as $pedido) {
  6977.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6978.                     $jaExisteNaLista true;
  6979.                 }
  6980.             }
  6981.             
  6982.             foreach ($pedidosDataPendenteAdmin as $pedido) {
  6983.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6984.                     $jaExisteNaLista true;
  6985.                 }
  6986.             }
  6987.             
  6988.             foreach ($pedidosDatabaixado as $pedido) {
  6989.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6990.                     $jaExisteNaLista true;
  6991.                 }
  6992.             }
  6993.             
  6994.             foreach ($pedidosDataRecebido as $pedido) {
  6995.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  6996.                     $jaExisteNaLista true;
  6997.                 }
  6998.             }
  6999.             
  7000.             foreach ($pedidosDataCotacao as $pedido) {
  7001.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  7002.                     $jaExisteNaLista true;
  7003.                 }
  7004.             }
  7005.             
  7006.             foreach ($pedidosDataAguardandoPagamento as $pedido) {
  7007.                 if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
  7008.                     $jaExisteNaLista true;
  7009.                 }
  7010.             }
  7011.             
  7012.             if(!$jaExisteNaLista) {
  7013.                 $pedidos $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilter($fieldPassed$pedidoFiltrado$tipo);
  7014.                 foreach ($pedidos as $pedido) {
  7015.                     $pedidosDatabaixado[] = $this->makeProdutoData($pedido);
  7016.                 }
  7017.             }
  7018.         }
  7019.         
  7020.         $mensagensChat $this->getAllMensagensChat();
  7021.         $temMensagemNaoLida false;
  7022.         foreach ($mensagensChat as $mensagemChat) {
  7023.            if(!$mensagemChat['isLida']){
  7024.                 $temMensagemNaoLida true;
  7025.                 break;
  7026.            } 
  7027.         }
  7028.         
  7029.         return [
  7030.             'pendentes'             => $pedidosDataPendentes
  7031.             'aceitos'               => $pedidosDataAceitos
  7032.             'entregues'             => $pedidosDataEntregues
  7033.             'transito'              => $pedidosDataTransito
  7034.             'pendentes_admin'       => $pedidosDataPendenteAdmin
  7035.             'baixados'              => $pedidosDatabaixado
  7036.             'recebidos'             => $pedidosDataRecebido,
  7037.             'cotacao'               => $pedidosDataCotacao,
  7038.             'aguardando_pagamento'  => $pedidosDataAguardandoPagamento,
  7039.             'naoLidos'              => $this->getPedidosNaoLidos(),
  7040.             'mensagensChat'         => $this->getAllMensagensChat(),
  7041.             'temMensagemNaoLida'    => $temMensagemNaoLida
  7042.         ];
  7043.     }
  7044.     
  7045.     private function getProduto($apiKeyStore$codigoProduto$client$xml=false) {
  7046.         $format 'json';
  7047.         if($xml){
  7048.             $format 'xml';
  7049.         }
  7050.         $response $client->request(
  7051.             'GET',
  7052.             SincronizacaoController::URL_API_BLING '/produto/'.$codigoProduto.'/'.$format,
  7053.             [
  7054.                 'query' => [
  7055.                     'apikey'  => $apiKeyStore,
  7056.                     'estoque' => 'S',
  7057.                     'imagem'  => 'S',
  7058.                     'situacao' => 'A'
  7059.                 ]
  7060.             ]
  7061.         );
  7062.         $statusCode $response->getStatusCode();
  7063.         if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
  7064.             if($xml){
  7065.                 return $response->getContent();
  7066.             }
  7067.             $content $response->toArray();
  7068.             return $content;
  7069.         } else {
  7070.             return [];
  7071.         }
  7072.         return [];
  7073.     }
  7074.     
  7075. }