<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\EntregaPedido;
use App\Entity\PedidoAcumulado;
use App\Entity\ProdutoBling;
use App\Entity\User;
use App\Entity\MensagemMural;
use App\Entity\ValeSolicitacao;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use App\Entity\MensagemColeta;
use Symfony\Component\HttpKernel\KernelInterface;
use Symfony\Bundle\FrameworkBundle\Console\Application;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\BufferedOutput;
use Doctrine\ORM\EntityManagerInterface;
use Dompdf\Dompdf;
use Dompdf\Options;
use App\Entity\LancamentoClienteDrive;
use App\Entity\ClienteDrive;
use App\Services\BlingService;
use App\Services\LogAcoesService;
use App\Entity\PagamentoPedidoCreditoDebito;
use App\Entity\ContatoBling;
use App\Entity\LancamentoFinanceiroColaborador;
use App\Entity\OrdemServico;
use App\Entity\LogAcoes;
use App\Entity\EntregaRoute;
use App\Entity\DemandaPedido;
class AppExternoController extends BaseController
{
################ UPLOAD INDIVIDUAL
/**
* @Route("/upload_imagem_open", name="upload_imagem_open", methods={"GET"})
*/
public function uploadImageOpen(Request $request): Response
{
return $this->render('upload_imagem/index.html.twig');
}
/**
* @Route("/acesso_direto_motorista", name="acesso_direto_motorista", methods={"GET"})
*/
public function acessoDiretoMotorista(Request $request): Response
{
$usuarios = [];
$colaboradores = $this->getDoctrine()->getRepository(User::class)->findBy([], ['email'=>'asc']);
foreach ($colaboradores as $colaborador) {
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'])){
continue;
}
$usuarios[] = [
'id' => $colaborador->getId(),
'name' => strtoupper($colaborador->getEmail()),
'email' => $colaborador->getEmail(),
];
}
return $this->render('upload_imagem/index-motorista.html.twig', ['colaboradores'=>$usuarios]);
}
################ UPLOAD INDIVIDUAL
/**
* @Route("/app-externo/pedidos_proximos", name="pedidos_proximos", methods={"POST"})
*/
public function pedidosProximos(Request $request): Response
{
$pedidos = [];
$data = json_decode($request->getContent(), false);
$pedidoEncontado = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
if(!$pedidoEncontado instanceof EntregaPedido) {
return new JsonResponse($pedidos, 200);
}
if($pedidoEncontado->getLatitude()==null || $pedidoEncontado->getLongitude()==null) {
return new JsonResponse($pedidos, 200);
}
// Exemplo de uso
$latitude = $pedidoEncontado->getLatitude();
$longitude = $pedidoEncontado->getLongitude();
$maxDistance = $data->raio;
//$statuses = ['pendente', 'recebido', 'cotaca', 'pendente_admin', 'aguardando_pagamento'];
$statuses = ['pendente'];
$results = $this->getDoctrine()->getRepository(EntregaPedido::class)
->findNearbyLocationsWithStatus($latitude, $longitude, $maxDistance, $statuses);
foreach ($results as $location) {
if($location['id']==$data->id) {
continue;
}
$numeroPedido = $location['pedido'];
if($numeroPedido=='' || $numeroPedido==null) {
$numeroPedido = $location['nota_fiscal'];
}
$distancia = number_format($location['distance'], 3);
$link = 'https://www.google.com/maps?q='.$location['latitude'].','.$location['longitude'];
$pedidos[] = ['id'=>$location['id'], 'pedido'=>$numeroPedido, 'distancia'=>$distancia, 'coordenadas'=>$location['latitude'].','.$location['longitude'], 'link'=>$link];
}
return new JsonResponse($pedidos, 200);
}
/**
* @Route("/app-externo/decodifica-endereco", name="decodifica_endereco")
*/
public function decodificaEnderecoAction(Request $request): Response
{
$address = 'Rua 209, 100, , Setor Coimbra, Goiânia/GO, 74.530-070, ';
$coordenadas = $this->decodificaEndereco($address);
return new JsonResponse($coordenadas, 200);
/*
46388
latitude: -16.6762553,
longitude: -49.292202
-16.675385, -49.289547
UPDATE entrega_pedido set latitude=-16.675385, longitude=-49.289547 WHERE id=9393
Apagar pois é original
-16.676255, -49.292202
UPDATE entrega_pedido set latitude=-16.676255, longitude=-49.292202 WHERE id=10873 === Pedido 47766
*/
}
public function decodificaEndereco($address)
{
// Endereço que você deseja converter
//$address = "Rua 205, 641, QD 98 LT 83A ST COIMBRA, St Coimbra, Goiânia/GO, 74530030,";
// Sua chave de API do Google
$apiKey = "AIzaSyBpmGesyT1jy7cdCtdDXwptTseDfBzxiGc";
// Formatar o endereço para uso na URL da API
$address = urlencode($address);
// URL da API de Geocoding do Google
$url = "https://maps.googleapis.com/maps/api/geocode/json?address={$address}&key={$apiKey}";
// Inicializar cURL
$ch = curl_init();
// Configurar as opções do cURL
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Executar a requisição e obter a resposta
$response = curl_exec($ch);
// Verificar se houve algum erro
if(curl_errno($ch)) {
return false;
exit;
}
// Fechar o cURL
curl_close($ch);
// Decodificar a resposta JSON
$responseData = json_decode($response, true);
$coordenadas = [];
// Verificar o status da resposta
if($responseData['status'] == 'OK') {
// Obter as coordenadas
$latitude = $responseData['results'][0]['geometry']['location']['lat'];
$longitude = $responseData['results'][0]['geometry']['location']['lng'];
$coordenadas['latitude'] = $latitude;
$coordenadas['longitude'] = $longitude;
} else {
return false;
}
return $coordenadas;
}
/**
* @Route("/app-externo/lista-log-acoes/{data_inicial}/{data_final}", name="lista_logs_acoes")
*/
public function listaLogsAcoes(Request $request, HttpClientInterface $client, $data_inicial, $data_final): Response
{
$logsData = [];
if($this->isAdmin()) {
$logsEntity = $this->getDoctrine()->getRepository(LogAcoes::class)->getLogs($data_inicial, $data_final);
foreach ($logsEntity as $log) {
$logsData[] = [
'id' => $log->getId(),
'pedido' => $log->getPedido(),
'origem' => $log->getOrigem(),
'acao' => $log->getAcao(),
'usuario' => $log->getUsuario()->getEmail(),
'data' => $log->getCreatedAt()->format('d/m/Y H:i')
];
}
}
return new JsonResponse($logsData, 200);
}
private function getStatusCorretoNome($status) {
$status = strtoupper($status);
switch ($status) {
case 'PENDENTE':
$status = 'À Entregar';
break;
case 'RECEBIDO':
$status = 'Em Andamento';
break;
case 'TRANSITO':
$status = 'Em Trânsito';
break;
case 'ENTREGUE':
$status = 'À Finalizar';
break;
case 'PENDENTE_ADMIN':
$status = 'Pendente';
break;
case 'COTACAO':
$status = 'Cotação';
break;
case 'AGUARDANDO_PAGAMENTO':
$status = 'Aguardando Pagamento';
break;
case 'ACEITO':
$status = 'Aceito';
break;
default:
// code...
break;
}
return $status;
}
function dentroIntervaloAbrirPedidosPendentes() {
$agora = new \DateTime();
$horaAtual = $agora->format('H:i');
// Definir os intervalos de tempo permitidos
$intervalos = [
['08:00', '08:30'],
['10:00', '10:30'],
['13:00', '14:00']
];
foreach ($intervalos as $intervalo) {
$inicio = $intervalo[0];
$fim = $intervalo[1];
if ($horaAtual >= $inicio && $horaAtual <= $fim) {
return true;
}
}
return false;
}
/**
* @Route("/app-externo/pedidos-pendentes-cadastro", name="pedidos_pendentes_cadastro")
*/
public function pedidosPendentesCadastro(Request $request, HttpClientInterface $client): Response
{
$pedidosPendentes = [];
if($this->dentroIntervaloAbrirPedidosPendentes()) {
if($this->isAdmin() || $this->getIsVendedor()) {
$pedidosImportados = $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtualWithData($this->getUser()->getEmail());
foreach ($pedidosImportados as $pedidoImportado) {
$pedidoEncontado = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoImportado['pedido']]);
if(!$pedidoEncontado instanceof EntregaPedido){
$pedidosPendentes[] = ['pedido'=>$pedidoImportado['pedido']];
}
}
}
}
return new JsonResponse($pedidosPendentes, 200);
}
/**
* @Route("/app-externo/conta-estoque", name="app_externo_conta_sku")
*/
public function contaEstoque(Request $request, HttpClientInterface $client): Response
{
if($request->get('sku')){
$sku = $request->get('sku');
// Pega todos os pedidos à entregar
$pedidosAEntregar = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosContagemEstoque();
$totalReservados = 0;
$strInfo = '';
foreach ($pedidosAEntregar as $pedido) {
$pedidoFeed = $this->contaOcorrenciasDeProdutoNoPedido($pedido, $sku);
$totalReservados +=$pedidoFeed['estoqueReal'];
$strInfo .=$pedidoFeed['info'];
}
$script = 'const valorContado = prompt("Informe o total contado do produto no estoque físico: '.$sku.'");';
$script .= 'const valorReservados = '.$totalReservados.';console.log("valorReservados: " + valorReservados);console.log("valorContado: " + valorContado);console.log("Total de pedidos: '.count($pedidosAEntregar).'\n\n'.$strInfo.'");';
$script .= 'var valorCorreto = valorContado-valorReservados;';
$script .= 'const info = "'.$strInfo.'\n\n";';
$script .= 'alert("Alimentar no Bling: " + valorCorreto + "\n\n" + info);window.close();';
echo '<script>'.$script.'</script>';
}
exit;
}
private function contaOcorrenciasDeProdutoNoPedido($pedido, $sku) {
$totalReservados = 0;
$itens = $pedido->getItensPedido();
if($itens==null || $itens=='') {
return ['estoqueReal'=>$totalReservados,'info'=>''];
}
$itens = json_decode($itens);
$infoStr = '';
$status = $pedido->getStatus();
$status = strtoupper($status);
switch ($status) {
case 'PENDENTE':
$status = 'À Entregar';
break;
case 'RECEBIDO':
$status = 'Em Andamento';
break;
case 'TRANSITO':
$status = 'Em Trânsito';
break;
case 'ENTREGUE':
$status = 'À Finalizar';
break;
case 'PENDENTE_ADMIN':
$status = 'Pendente';
break;
case 'COTACAO':
$status = 'Cotação';
break;
case 'AGUARDANDO_PAGAMENTO':
$status = 'Aguardando Pagamento';
break;
case 'ACEITO':
$status = 'Aceito';
break;
default:
// code...
break;
}
foreach ($itens as $item) {
if($item->codigo==$sku) {
if($status!='Em Trânsito' && $status!='Aceito' && $status!='À Finalizar'){
$totalReservados += $item->quantidade;
}
$infoStr .= 'Pedido: ' . $pedido->getPedido() . ' - Status: '.$status.' - Qtd: ' . $item->quantidade . '\n';
}
}
return ['estoqueReal'=>$totalReservados,'info'=>$infoStr];
}
/**
* @Route("/app-externo/print-os/{id}", name="print_os", methods={"GET"})
*/
public function printOS(Request $request, HttpClientInterface $client, $id): Response
{
$os = $this->getDoctrine()->getRepository(OrdemServico::class)->find(intval($id));
if(!$os instanceof OrdemServico) {
return new JsonResponse([], 400);
}
$css = '
body,html{
margin-top:10px;
margin-bottom:10px;
}
.page_break { page-break-before: always; }
.th_header{
text-align:center;
font-weight:bold;
}
';
$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>';
$body = $img . '<h4 style="text-align:center;font-size:20px;padding-top:3px;margin-bottom:10px;">POLLO MÓVEIS PARA ESCRITÓRIO</h4>
<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>';
$body .= '<div>
<strong style="text-align:center;padding-bottom:16px;display:block;">Descrição da OS</strong>
<div>'.nl2br($os->getDescricao()).'</div>
</div>';
$htmlBase = '<!DOCTYPE html>
<html>
<head>
<title>Ordem de serviço - Pollo Móveis</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style>'.$css.'</style>
</head>
<body>
'.$body.'
</body>
</html>';
if (get_magic_quotes_gpc()) {
$htmlBase = stripslashes($htmlBase);
}
$options = new Options();
$options->set('defaultFont', 'Helvetica');
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($htmlBase);
$dompdf->setPaper('A4');
// Renderize o PDF (processa HTML em PDF)
$dompdf->render();
// Obtém o conteúdo do PDF gerado
$output = $dompdf->output();
// Configuração da resposta HTTP para exibir o PDF no navegador
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="relatorio-credito-debito-pollo-distribuidora.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// Envia o conteúdo do PDF para o navegador
echo $output;
exit;
}
/**
* @Route("/app-externo/add-os", name="add_os", methods={"POST"})
*/
public function addOS(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$os = new OrdemServico();
$os->setDescricao($data->textNewOs);
$os->setStatus('pendente');
$os->setCreatedAt(new \DateTime());
$os->setNumero(mt_rand(10000000, 99999999));
$this->getDoctrine()->getManager()->persist($os);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/apaga-os", name="apaga_os", methods={"POST"})
*/
public function apagaOS(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$os = $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
if(!$os instanceof OrdemServico) {
return new JsonResponse([], 400);
}
$os->setDeletedAt(new \DateTime());
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/baixa-os", name="baixa_os", methods={"POST"})
*/
public function baixaOS(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$os = $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
if(!$os instanceof OrdemServico) {
return new JsonResponse([], 400);
}
$os->setStatus('baixado');
$os->setBaixadoPor($this->getUser());
$os->setBaixadoAt(new \DateTime());
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/aceita-os", name="aceita_os", methods={"POST"})
*/
public function aceitaOS(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$os = $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
if(!$os instanceof OrdemServico) {
return new JsonResponse([], 400);
}
// if(($os->getSolicitarMontagem() && $os->getSolicitarMontagemSaoJose()) || ($os->getSolicitarMontagemSaoJose() && $os->solicitarSeparacaoSaoJose())){
// } else {
// return new JsonResponse([], 400);
// }
$os->setStatus('aceito');
$os->setAceitoPor($this->getUser());
$os->setAceitoAt(new \DateTime());
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/edit-os", name="edit_os", methods={"POST"})
*/
public function editOS(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$os = $this->getDoctrine()->getRepository(OrdemServico::class)->find($data->id);
if(!$os instanceof OrdemServico) {
return new JsonResponse([], 400);
}
$os->setDescricao($data->texto);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/lista-os", name="lista_os", methods={"GET"})
*/
public function listaOS(Request $request, HttpClientInterface $client): Response
{
$data = [];
$oss = $this->getDoctrine()->getRepository(OrdemServico::class)->findBy(['deletedAt'=>null], ['createdAt'=>'desc']);
foreach ($oss as $os) {
if($os->getStatus()=='baixado'){
continue;
}
$data[] = [
'id' => $os->getId(),
'numero' => str_pad($os->getId(), 4, "0", STR_PAD_LEFT),
'texto' => $os->getDescricao(),
'status' => $os->getStatus(),
'createdAt' => $os->getCreatedAt()->format('d/m/Y às H:i'),
'aceitoAt' => ($os->getAceitoAt()) ? $os->getAceitoAt()->format('d/m/Y H:i') : '',
'aceitoPor' => ($os->getAceitoPor()) ? $os->getAceitoPor()->getEmail() : ''
];
}
return new JsonResponse($data, 200);
}
/**
* @Route("/app-externo/update-obs-emergencial", name="update_obs_emergencial", methods={"POST"})
*/
public function updateObsEmergencial(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
if(!$pedido instanceof EntregaPedido) {
return new JsonResponse([], 400);
}
$pedido->setObsEmergencial($data->obsEmergencial);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/deletar_pedido_customizado", name="deletar_pedido_customizado", methods={"POST"})
*/
public function deleteItensPedido(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse([], 400);
}
$pedido->setRazaoSocialCustomizado(null);
$pedido->setEnderecoSocialCustomizado(null);
$pedido->setItensPedidoCustomizado(null);
$pedido->setFreteCustomizado(null);
$pedido->setClienteCustomizado(null);
$pedido->setFormaPagamentoCustomizado(null);
$pedido->setVendedorCustomizado(null);
$pedido->setDesconto(null);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/salvar_pedido_customizado", name="salvar_pedido_customizado", methods={"POST"})
*/
public function saveItensPedido(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse([], 400);
}
$itens = $data->itensPedidoCustomizado;
$itensRecalculate = [];
foreach ($itens as $item) {
if(strstr($item->valorunidade, 'R$')){
$valor = preg_replace("/[^0-9,.]/", "", $item->valorunidade);
$valor = str_replace(".", "", $valor);
$valor = str_ireplace(',','.', $valor);
} else {
$valor = $item->valorunidade;
}
$valorTotal = $valor * $item->quantidade;
$itensRecalculate[] = [
'titulo' => $item->titulo,
'codigo' => $item->codigo,
'valorunidade' => number_format($valor, 2, '.', ''),
'quantidade' => abs($item->quantidade),
'valorTotal' => $valorTotal
];
}
$valorFrete = preg_replace("/[^0-9,.]/", "", $data->freteCustomizado);
$valorFrete = str_replace(".", "", $valorFrete);
$valorFrete = str_ireplace(',','.', $valorFrete);
$valorDesconto = preg_replace("/[^0-9,.]/", "", $data->desconto);
$valorDesconto = str_replace(".", "", $valorDesconto);
$valorDesconto = str_ireplace(',','.', $valorDesconto);
$pedido->setRazaoSocialCustomizado($data->razaoSocialCustomizado);
$pedido->setEnderecoSocialCustomizado($data->enderecoSocialCustomizado);
$pedido->setItensPedidoCustomizado(json_encode($itensRecalculate));
$pedido->setFreteCustomizado($valorFrete);
$pedido->setClienteCustomizado($data->clienteCustomizado);
$pedido->setFormaPagamentoCustomizado($data->formaPagamentoCustomizado);
$pedido->setVendedorCustomizado($data->vendedorCustomizado);
$pedido->setDesconto($valorDesconto);
//$pedido->setDesconto($data->desconto);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/itens_pedido/{pedido}", name="itens_pedido", methods={"GET"})
*/
public function getItensPedido(Request $request, HttpClientInterface $client, $pedido): Response
{
$itens = $this->getItensPedidoSingle($client, $pedido); //44286
return new JsonResponse($itens, 200);
}
private function getItensPedidoSingle($client, $numero) {
$itens = [];
$response = $client->request(
'GET',
SincronizacaoController::URL_API_BLING . '/pedido/'.$numero.'/json/',
[
'query' => [
'apikey' => SincronizacaoController::KEY_API_POLLO
]
]
);
$statusCode = $response->getStatusCode();
if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
$content = $response->toArray();
if(isset($content['retorno'])) {
if(isset($content['retorno']['pedidos'])) {
if(count($content['retorno']['pedidos']) > 0) {
if(isset($content['retorno']['pedidos'][0])) {
$pedido = $content['retorno']['pedidos'][0]['pedido'];
if(!empty($pedido['itens'])){
foreach ($pedido['itens'] as $item) {
$item = $item['item'];
$valorTotal = $item['valorunidade'] * $item['quantidade'];
$itens[] = [
'titulo' => $item['descricao'],
'codigo' => $item['codigo'],
'valorunidade' => number_format($item['valorunidade'], 2, '.', ''),
'quantidade' => abs($item['quantidade']),
'valorTotal' => $valorTotal
];
}
}
}
}
}
}
}
return $itens;
}
/**
* @Route("/app-externo/salvar_info_geovair", name="salvar_info_geovair", methods={"POST"})
*/
public function salvarInfoGeovair(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse([], 400);
}
$estaPago = ($data->estaPago=='true') ? true : false;
$emitirNf = ($data->emitirNf=='true') ? true : false;
$emitirBoleto = ($data->emitirBoleto=='true') ? true : false;
$receberEntregaGeovair = ($data->receberEntregaGeovair=='true') ? true : false;
$pedido->setEnviarGeovair(new \DateTime());
$pedido->setGeovairFormaPagamento($data->formaPagamento);
$pedido->setGeovairEstaPago($estaPago);
$pedido->setGeovairEmitirNf($emitirNf);
$pedido->setGeovairEmitirBoleto($emitirBoleto);
$pedido->setGeovairReceberEntregaColeta($receberEntregaGeovair);
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
$messageBody = "*Dar andamento no pedido: Nº $numeroPedido*\n*Conforme instruções.*\n\n";
$messageBody .= 'Imprimir: *' . $pedido->getTipoDocumento() . "*\n";
$messageBody .= 'Forma de pagamento: *' . $pedido->getFormaPagamento() . "*\n";
$messageBody .= 'Está pago: *' . $pedido->getEstaPago() . "\n";
$messageBody .= 'Receber na entrega: *' . $pedido->getReceberNaEntrega() . "*\n";
$messageBody .= 'Meio de entrega: *' . $pedido->getMeioEntrega() . "*\n";
$messageBody .= 'Montar Móveis: *' . $pedido->getMontarMoveis() . "*\n";
$messageBody .= 'Embalagem: *' . $pedido->getEmbalagem() . "*\n";
$messageBody .= 'Período da Entrega: *' . $pedido->getPeriodoEntrega() . "*\n";
$messageBody .= 'Link Pedido: ' . "https://app.moveispollo.com.br/pedido/$numeroPedido";
$img = 'https://polo.srvtmp.com.br/andamento.png?v=3';
$this->sendMensagemViaWhatsapp("img", '5562993602042', $messageBody, $img, null, null); // Geovair
$this->sendMensagemViaWhatsapp("img", '5562981352530', $messageBody, $img, null, null); // Mateus
$this->sendMensagemViaWhatsapp("img", '5562995698482', $messageBody, $img, null, null); // Samuel
//$this->sendMensagemViaWhatsapp("img", '5562983281823', $messageBody, $img, null, null); // Samuel
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/ids_produtos_bling", name="ids_produtos_bling", methods={"GET"})
*/
public function idsProdutosBling(Request $request): Response
{
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
$produtosBling = $this->getDoctrine()->getRepository(ProdutoBling::class)->findAll();
$ids = [];
foreach ($produtosBling as $prod) {
if($prod->getIdBling())
$ids[] = ['id'=>$prod->getIdBling(), 'sku'=>$prod->getCodigo()];
}
return new JsonResponse($ids, 200);
}
###### V2
/**
* @Route("/app-externo/v2", name="app_externo_v2")
*/
public function indexv2(Request $request): Response
{
$abrePedidoParaCadastro = 'false';
if($request->get('add_card')){
$abrePedidoParaCadastro = 'true';
}
$hoje = new \DateTime();
return $this->render('app_externo/index-v2.html.twig', [
'controller_name' => 'AppExternoController',
'usario' => $this->getUser()->getEmail(),
'isAdmin' => $this->getIsAdmin(),
'isEntregador' => $this->getIsEntregador(),
'isEntregadorAux' => $this->getIsEntregadorAux(),
'isVendedor' => $this->getIsVendedor(),
'isSeparador' => $this->getIsSeparador(),
'menuContextoCard' => $this->getMenuContextoCard(),
'dataHoje' => $hoje->format('Y-m-d'),
// 'faturamentoAtual' => __DIR__,
'faturamentoAtual' => number_format($this->getFaturamentoAtual(), 2, ',', '.'),
'abreNovoPedido' => $abrePedidoParaCadastro,
'pedidoNovoParaAdd' => $request->get('add_card'),
'temAlgumValePendente' => $this->temAlgumValePendente()
]);
}
/**
* @Route("/crons", name="app_crons")
*/
public function cronsPageAction(Request $request): Response
{
return $this->render('app_externo/index-crons.html.twig');
}
/**
* @Route("/crons/execute/{acao}", name="app_crons_execute")
*/
public function cronsExecuteAction(Request $request, KernelInterface $kernel, $acao): Response
{
$acaoEncontrada = false;
if($acao=='credito_debito'){
$acaoEncontrada = true;
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'app:acoes-pedidos-diario',
'--somentedrive' => 'sim'
]);
} else if($acao=='promocoes') {
$acaoEncontrada = true;
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'app:envia-promocao-agendada'
]);
}
if($acaoEncontrada){
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
// return new Response(""), if you used NullOutput()
return new Response($content);
}
exit('Nenhum comando encontrado');
}
###### DRIVE
/**
* @Route("/app-externo/itens_pagos_drive", name="itens_pagos_drive", methods={"POST"})
*/
public function itens_pagos_drive(Request $request): Response
{
$data = json_decode($request->getContent(), false);
foreach ($data->itens as $item) {
$lancamento = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($item->id);
if($lancamento instanceof LancamentoClienteDrive) {
$lancamento->setIsCalcula($item->isCalcula);
$lancamento->setIsPago($item->isPago);
$this->getDoctrine()->getManager()->flush();
}
}
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/drive", name="app_drive")
*/
public function drivePageAction(Request $request): Response
{
$hoje = new \DateTime();
return $this->render('app_externo/drive-index.html.twig', [
'primeiro_dia_mes' => $hoje->format('Y') . '-'.$hoje->format('m').'-01',
'ultimo_dia_mes' => $hoje->format('Y-m-d'),
'mesAtualDrive' => $hoje->format('m')
]);
}
/**
* @Route("/app-externo/pagamento-pedido/delete/{id}", name="pagamentos_pedido_delete", methods={"GET"})
*/
public function deletePagamentoPedidoAction(Request $request, $id)
{
$lancamento = $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->find($id);
if(!$lancamento instanceof PagamentoPedidoCreditoDebito) {
return new JsonResponse([], 400);
}
$this->getDoctrine()->getManager()->remove($lancamento);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/list-pagamento-pedido/{pedido}", name="pagamentos_pedidos", methods={"GET"})
*/
public function clientesDriveLancamentosAction(Request $request, $pedido)
{
$pedidoRequest = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($pedido);
if(!$pedidoRequest instanceof LancamentoClienteDrive){
return new JsonResponse([], 400);
}
$pagamentos = $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->findBy(['pedido'=>$pedidoRequest],['pagoAt'=>'asc']);
$pagamentosData = [];
foreach ($pagamentos as $pagamento) {
$pagamentosData[] = [
'id' => $pagamento->getId(),
'valor' => number_format($pagamento->getValor(), 2, ',', '.'),
'obs' => $pagamento->getObs(),
'tipo' => $pagamento->getTipo(),
'data' => $pagamento->getPagoAt()->format('d/m/Y'),
];
}
return new JsonResponse($pagamentosData, 200);
}
/**
* @Route("/app-externo/add-pagamento-pedido", name="add_pagamento_pedido", methods={"POST"})
*/
public function createPagamentoPedido(Request $request): JsonResponse
{
$entityManager = $this->getDoctrine()->getManager();
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
if(!$pedido instanceof LancamentoClienteDrive){
return new JsonResponse([], 400);
}
$date = \DateTime::createFromFormat('Y-m-d', $data->data);
$valor = preg_replace("/[^0-9,.]/", "", $data->valor);
$valor = str_replace(".", "", $valor);
$valor = str_ireplace(',','.', $valor);
$pagamento = new PagamentoPedidoCreditoDebito();
$pagamento->setTipo($data->tipo);
$pagamento->setPedido($pedido);
$pagamento->setValor($valor);
$pagamento->setPagoAt($date);
if(!empty($data->nota)){
$pagamento->setNota($data->nota);
}
if(!empty($data->obs)){
$pagamento->setObs($data->obs);
}
$pagamento->setCreatedAt(new \DateTime());
$entityManager->persist($pagamento);
$entityManager->flush();
return new JsonResponse(['message' => 'Pagamento criado com sucesso'], 200);
}
/**
* @Route("/app-externo/atualiza-valores-drive", name="atualiza_valores_drive", methods={"GET"})
*/
public function atualizaValoresDrive(KernelInterface $kernel)
{
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'app:acoes-pedidos-diario',
'--somentedrive' => 'sim'
]);
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
// return new Response(""), if you used NullOutput()
return new Response($content);
}
/**
* @Route("/app-externo/credito-debito-pdf/{id}/{mes}/{zap}", name="clientes_drive_pdf", methods={"GET"})
*/
public function clientesDriveRelatorioPdfAction(Request $request, $id, $mes, $zap)
{
$cliente = $this->getDoctrine()->getRepository(ClienteDrive::class)->find($id);
if(!$cliente instanceof ClienteDrive) {
exit();
}
// Obtém a data atual
$dataAtual = new \DateTime();
$dataFiltroInicial = new \DateTime($dataAtual->format('Y-m-01'));
$dataFiltroFinal = new \DateTime($dataAtual->format('Y-m-t'));
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
);
$logo = "https://pollodistribuidora.com.br/wp-content/uploads/2022/05/pollodistribuidora.png";
$dataLogo = file_get_contents($logo, false, stream_context_create($arrContextOptions));
$base64Logo = 'data:image/jpeg;base64,' . base64_encode($dataLogo);
$hoje = new \DateTime();
$body = "
<div style='text-align:center;'><img src='$base64Logo'/></div>
<h4 style='text-align:center;padding-bottom:0;margin-bottom:0;'>
POLLO MOVEIS - RELATÓRIO DE CRÉDITOS E DÉBITOS</h4><hr/>";
$body .= '<p style="text-align:center">
<strong>CLIENTE: </strong> '.$cliente->getNome().'<br/>
<span style="color:green;margin-top:10px;display:inline-block;"><strong>PERÍODO:</strong> '.$dataFiltroInicial->format('d/m/Y').' - ' . $dataFiltroFinal->format('d/m/Y').
'<span></p>';
$rowsCredito = [];
$rowsDebito = [];
$totalCreditos = 0;
$contDebitosLido = 0;
$contCreditosLido = 0;
$totalLancamentosIndividuais = 0;
//->lancamentosPorPeriodo($cliente, $dataInicial, $dataFinal);
$totalDebitos = 0;
$lancamentosCredito = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)
->lancamentosPorPeriodo($cliente, $mes, 'credito');
$contCreditos = count($lancamentosCredito);
$lancamentosDebito = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)
->lancamentosPorPeriodo($cliente, $mes, 'debito');
$contDebitos = count($lancamentosDebito);
$lancamentos = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)
->lancamentosPorPeriodo($cliente, $mes);
foreach($lancamentos as $lancamento) {
$numeroPedido = '<a href="https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' . $lancamento->getNota().'&nf=n">'.$lancamento->getNota().'</a>';
$pedidoEntity = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$lancamento->getNota()]);
if($pedidoEntity instanceof EntregaPedido){
if($pedidoEntity->getNotas()!=null && $pedidoEntity->getNotas()!=''){
$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>';
}
}
if($lancamento->getTipo()=='credito'){
$contCreditosLido++;
$rowsCredito[] = '<tr>
<td style="text-align:center;font-size:11px;">'.$lancamento->getData()->format('d/m/Y').'</td>
<td style="text-align:center;font-size:11px;">'.$numeroPedido.'</td>
<td style="color:green;text-align:right;font-size:11px;" colspan="2">R$ '.number_format($lancamento->getValor(), 2, ',', '.').'</td>
<td style="text-align:left;font-size:11px;" width="25%">'.$lancamento->getObs().'</td>
<tr>';
$totalCreditos +=$lancamento->getValor();
if($contCreditosLido==$contCreditos){
$rowsCredito[] = '<tr>
<td colspan="4" style="text-align:right;font-size:11px;"><strong>Total</strong></td>
<td style="color:green;text-align:left;font-size:11px;">R$ '.number_format($totalCreditos, 2, ',', '.').'</td>
<tr>';
}
} else {
$lancamentos = $this->getLancamentosPorPedido($lancamento->getId());
$totalLancamentosIndividuais += $lancamentos['total'];
$tdLancamentos = '';
foreach ($lancamentos['lancamentos'] as $lancamentoIndividual){
$tdLancamentos .= '<tr>
<td style="color:blue;font-size:11px;">'.$lancamentoIndividual['valor'].'</td>
<td style="color:blue;font-size:11px;">'.$lancamentoIndividual['data'].'</td>
<td style="color:blue;font-size:11px;">'.$lancamentoIndividual['tipo'].'</td>
</tr>';
}
$tableLancamentos = (count($lancamentos['lancamentos'])>0) ? '<table width="100%" border="0">'.$tdLancamentos.'</table>' : '';
$contDebitosLido++;
$backGroundPago = '';
$isPago = '';
if($lancamento->getIsPago()){
$backGroundPago = 'style="background-color:#7FFFD4 !important;"';
$isPago=" - PG";
}
$rowsDebito[] = '<tr '.$backGroundPago.'>
<td style="text-align:center;font-size:11px;">'.$lancamento->getData()->format('d/m/Y').$isPago.'</td>
<td style="text-align:center;font-size:11px;">'.$numeroPedido.'</td>
<td style="color:red;text-align:right;font-size:11px;">R$ '.number_format($lancamento->getValor(), 2, ',', '.').'</td>
<td>'.$tableLancamentos.'</td>
<td style="text-align:left;font-size:11px;" width="25%">'.$lancamento->getObs().'</td>
<tr>';
if($lancamento->getIsCalcula()){
$totalDebitos +=$lancamento->getValor();
}
if($contDebitosLido==$contDebitos){
$rowsDebito[] = '<tr>
<td colspan="4" style="text-align:right;font-size:11px;"><strong>Total de débitos de pedidos</strong></td>
<td style="color:red;text-align:left;font-size:11px;">R$ '.number_format($totalDebitos, 2, ',', '.').'</td>
<tr>';
$rowsDebito[] = '<tr>
<td colspan="4" style="text-align:right;font-size:11px;"><strong>Valores pagos ligados aos pedidos</strong></td>
<td style="color:blue;text-align:left;font-size:11px;">R$ '.number_format($totalLancamentosIndividuais, 2, ',', '.').'</td>
<tr>';
}
}
}
$body .= '<table style="margin-top:20px;" width="100%" cellspacing="1" cellpadding="2" border="1">
<tr>
<td colspan="5" style="text-align:center;color:red;"><strong>Débitos</strong></td>
<tr>
<tr style="background-color:#ddd;">
<td style="text-align:center;font-size:11px;"><strong>Data</strong></td>
<td style="text-align:center;font-size:11px;"><strong>Pedido</strong></td>
<td style="text-align:center;font-size:11px;"><strong>À pagar</strong></td>
<td style="text-align:center;font-size:11px;"><strong>Pagamentos efetuados neste pedido</strong></td>
<td style="text-align:center;font-size:11px;"><strong>Observação</strong></td>
<tr>
'.implode('',$rowsDebito).'
</table>';
$body .= '<table style="margin-top:30px;" width="100%" cellspacing="1" cellpadding="2" border="1">
<tr style="background-color:#ddd;">
<td colspan="5" style="text-align:center;color:green;"><strong>Créditos fora dos pedidos</strong></td>
<tr>
<tr>
<td style="text-align:center;font-size:11px;"><strong>Data</strong></td>
<td style="text-align:center;font-size:11px;"><strong>Pedido</strong></td>
<td style="text-align:right;font-size:11px;" colspan="2"><strong>Valor</strong></td>
<td style="text-align:center;font-size:11px;"><strong>Observação</strong></td>
<tr>
'.implode('',$rowsCredito).'
</table>';
$totalCreditos += $totalLancamentosIndividuais;
$saldo = $totalCreditos - $totalDebitos;
$color = ($saldo>=0) ? 'green' : 'red';
$body .= '<p style="text-align:right;font-size:11px;"><strong>Saldo Total: </strong> <span style="color:'.$color.';">R$ '.number_format($saldo, 2, ',', '.').'</span><p>';
$htmlBase = '<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pollo Distribuidora - Relatório Créditos e Débitos Revendedor</title>
<style type="text/css">
</style>
<body>
'.$body.'
</body>
</html>';
if (get_magic_quotes_gpc()) {
$htmlBase = stripslashes($htmlBase);
}
$options = new Options();
$options->set('defaultFont', 'Helvetica');
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($htmlBase);
$dompdf->setPaper('A4');
// Renderize o PDF (processa HTML em PDF)
$dompdf->render();
// Obtém o conteúdo do PDF gerado
$output = $dompdf->output();
if($zap=='s') {
$nomeArquivoAmigavel = 'Relatório de Créditos e Débitos - Pollo Distribuidora';
$fileName = 'relatorio-credito-debito-pollo-distribuidora-'.$cliente->getCnpj();
$pathSave = '/www/wwwroot/gestor.moveispollo.com.br/public/' . $fileName . '.pdf';
file_put_contents($pathSave, $output);
$urlPdf = 'https://polo.srvtmp.com.br/' . $fileName . '.pdf';
$numeroTelefones = explode('|', $cliente->getTelefone());
if(count($numeroTelefones)>=1) {
$numeroTelefone = $this->filterCelular($numeroTelefones[0]);
$numeroTelefone = '55' . $numeroTelefone;
$this->sendMensagemViaWhatsapp('pdf', $numeroTelefone, $nomeArquivoAmigavel , null, $nomeArquivoAmigavel, $urlPdf, null);
}
// foreach ($numeroTelefones as $numeroTelefone) {
// $numeroTelefone = $this->filterCelular($numeroTelefone);
// $numeroTelefone = '55' . $numeroTelefone;
// $this->sendMensagemViaWhatsapp('pdf', $numeroTelefone, $nomeArquivoAmigavel , null, $nomeArquivoAmigavel, $urlPdf, null);
// }
// Apagar arquivo PDF
return new JsonResponse([], 200);
}
// Configuração da resposta HTTP para exibir o PDF no navegador
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="relatorio-credito-debito-pollo-distribuidora.pdf"');
header('Cache-Control: private, max-age=0, must-revalidate');
header('Pragma: public');
header('Expires: Sat, 26 Jul 1997 05:00:00 GMT');
header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
// Envia o conteúdo do PDF para o navegador
echo $output;
exit;
}
private function filterCelular($telefone) {
$telefone= trim(str_replace('/', '', str_replace(' ', '', str_replace('-', '', str_replace(')', '', str_replace('(', '', $telefone))))));
return $telefone;
}
function formatarTelefone($telefone) {
// Remove todos os caracteres não numéricos
$telefone = preg_replace('/[^0-9]/', '', $telefone);
// Aplica a formatação desejada
if (strlen($telefone) >= 10) {
// Formato para números com código de país e estado
$codigoPais = substr($telefone, 0, strlen($telefone) - 10);
$codigoEstado = substr($telefone, -10, 2);
$numeroLocal = substr($telefone, -8);
// Verifica se o número de telefone tem um dígito a mais no celular
if (strlen($numeroLocal) == 9) {
$numeroLocal = '9' . $numeroLocal; // Adiciona o 9 no início
}
return '+' . $codigoPais . ' (' . $codigoEstado . ') ' . substr_replace($numeroLocal, '-', 4, 0);
} else {
// Retorna o número original se não for possível formatar
return $telefone;
}
}
/**
* @Route("/app-externo/drive/clientes/deactivate", name="clientes_drive_deactivate", methods={"POST"})
*/
public function desativarClientesDriveAction(Request $request)
{
$data = json_decode($request->getContent(), false);
$cliente = $this->getDoctrine()->getRepository(ClienteDrive::class)->find($data->id);
if(!$cliente instanceof ClienteDrive){
return new JsonResponse([], 400);
}
$cliente->setIsActive(false);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/drive/clientes", name="clientes_drive", methods={"GET"})
*/
public function clientesDriveAction(Request $request)
{
$clientes = $this->getDoctrine()->getRepository(ClienteDrive::class)->findBy(['isActive'=>true],['nome'=>'asc']);
$clientesData = [];
foreach ($clientes as $cliente) {
$numeroTelefones = explode('|',$cliente->getTelefone());
$numeroTelefonesData = [];
foreach ($numeroTelefones as $numeroTelefone) {
$numeroTelefone = $this->filterCelular($numeroTelefone);
if(!empty($numeroTelefone)){
$numeroTelefone = '55' . $numeroTelefone;
$numeroTelefonesData[] = $numeroTelefone; //$this->formatarTelefone($numeroTelefone);
} else {
$numeroTelefonesData[] = 'Não informado';
}
}
$clientesData[] = [
'id' => $cliente->getId(),
'nome' => $cliente->getNome(),
'cnpj' => $cliente->getCnpj(),
'telefones' => implode(' - ', $numeroTelefonesData),
'obs' => $cliente->getObs()
];
}
return new JsonResponse($clientesData, 200);
}
/**
* @Route("/app-externo/drive/updateobs", name="drive_update_obs", methods={"POST"})
*/
public function updateObsDriveAction(Request $request)
{
$data = json_decode($request->getContent(), false);
if($data->tipo=='lancamento'){
$lancamento = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
if(!$lancamento instanceof LancamentoClienteDrive) {
return new JsonResponse([], 400);
}
} else {
$lancamento = $this->getDoctrine()->getRepository(ClienteDrive::class)->find($data->id);
if(!$lancamento instanceof ClienteDrive) {
return new JsonResponse([], 400);
}
}
$lancamento->setObs($data->obs);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/drive/updatevalor", name="drive_update_valor", methods={"POST"})
*/
public function updateValorDriveAction(Request $request)
{
$data = json_decode($request->getContent(), false);
$lancamento = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
if(!$lancamento instanceof LancamentoClienteDrive) {
return new JsonResponse([], 400);
}
$valor = preg_replace("/[^0-9,.]/", "", $data->valor);
$valor = str_replace(".", "", $valor);
$valor = str_ireplace(',','.', $valor);
$lancamento->setValor($valor);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/drive/lancamento/externo", name="lancamento_drive_externo", methods={"POST"})
*/
public function lancamentoClienteDriveExternoAction(Request $request, HttpClientInterface $client)
{
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
// Extrair as informações da requisição
$dados = explode('-', trim($request->get('requisicao')));
$valor = trim($dados[0]);
$tipoPagamento = trim($dados[1]);
$obs = null;
if(count($dados)>2){
$obs = trim($dados[2]);
}
$pedidoNumber = trim($request->get('pedido'));
$dataPedido = trim($request->get('data'));
$date = \DateTime::createFromFormat('d/m/Y', $dataPedido);
$valor = preg_replace("/[^0-9,.]/", "", $valor);
$valor = str_replace(".", "", $valor);
$valor = str_ireplace(',','.', $valor);
$pedido = $this->getDoctrine()
->getRepository(LancamentoClienteDrive::class)
->findOneBy(['nota' => $request->get('pedido')]);
if(!$pedido instanceof LancamentoClienteDrive){
return new JsonResponse(['message'=>'Pedido não encontrado'], 400);
}
$pagamento = $this->getDoctrine()
->getRepository(PagamentoPedidoCreditoDebito::class)
->findOneBy(['tipo' => $tipoPagamento, 'pedido'=>$pedido, 'valor'=>$valor, 'obs'=>$obs]);
if($pagamento instanceof PagamentoPedidoCreditoDebito){
return new JsonResponse(['message'=>'Este pagamento já foi lançado'], 400);
}
$pagamento = new PagamentoPedidoCreditoDebito();
$pagamento->setTipo($tipoPagamento);
$pagamento->setPedido($pedido);
$pagamento->setValor($valor);
$pagamento->setPagoAt($date);
$pagamento->setNota($pedidoNumber);
$pagamento->setObs($obs);
$pagamento->setCreatedAt(new \DateTime());
$this->getDoctrine()->getManager()->persist($pagamento);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/drive/lancamento/{id}", name="lancamento_drive", methods={"POST"})
*/
public function lancamentoClienteDriveAction(Request $request, $id)
{
$data = json_decode($request->getContent(), false);
$cliente = $this->getDoctrine()->getRepository(ClienteDrive::class)->find($id);
if(!$cliente instanceof ClienteDrive){
return new JsonResponse([], 400);
}
$date = \DateTime::createFromFormat('Y-m-d', $data->data);
$lancamento = new LancamentoClienteDrive();
$lancamento->setTipo('credito');
$valor = preg_replace("/[^0-9,.]/", "", $data->valor);
$valor = str_replace(".", "", $valor);
$valor = str_ireplace(',','.', $valor);
$lancamento->setCliente($cliente);
$lancamento->setData($date);
$lancamento->setNota($data->nota);
$lancamento->setValor($valor);
$lancamento->setTipo($data->tipo);
$lancamento->setObs($data->obs);
$lancamento->setCreatedAt(new \DateTime('now'));
$lancamento->setIsCalcula(true);
$this->getDoctrine()->getManager()->persist($lancamento);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/drive/lancamentos/cliente/{id}/{mes}", name="lancamento_clientes_drive", methods={"GET"})
*/
public function lancamentosClienteDriveAction(Request $request, $id, $mes)
{
$cliente = $this->getDoctrine()->getRepository(ClienteDrive::class)->find($id);
if(!$cliente instanceof ClienteDrive) {
return new JsonResponse([], 400);
}
$lancamentos = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->lancamentosPorPeriodo($cliente, $mes);
$lancamentosData = [];
$creditos = [];
$debitos = [];
$totalCreditos = 0;
$totalDebitos = 0;
$totalDebitosPagos = 0;
$saldo = 0;
$saldoPositivo = true;
$totalLancamentosIndividuais = 0;
foreach ($lancamentos as $lancamento) {
if($lancamento->getTipo()=='credito'){
$creditos[] = [
'id' => $lancamento->getId(),
'data' => $lancamento->getData()->format('d/m/Y'),
'nota' => $lancamento->getNota(),
'valor' => number_format($lancamento->getValor(), 2, ',', '.'),
'obs' => $lancamento->getObs(),
'isPago' => $lancamento->getIsPago(),
'isCalcula' => $lancamento->getIsCalcula(),
];
$totalCreditos +=$lancamento->getValor();
} else {
$lancamentos = $this->getLancamentosPorPedido($lancamento);
$totalLancamentosIndividuais += $lancamentos['total'];
$debitos[] = [
'id' => $lancamento->getId(),
'data' => $lancamento->getData()->format('d/m/Y'),
'nota' => $lancamento->getNota(),
'valor' => number_format($lancamento->getValor(), 2, ',', '.'),
'obs' => $lancamento->getObs(),
'isPago' => $lancamento->getIsPago(),
'isCalcula' => $lancamento->getIsCalcula(),
'lancamentos' => $lancamentos['lancamentos']
];
//$totalDebitos +=$lancamento->getValor();
if($lancamento->getIsCalcula()) {
$totalDebitos +=$lancamento->getValor();
}
}
}
$totalCreditos += $totalLancamentosIndividuais;
$saldo = $totalCreditos - $totalDebitos;
$saldoPositivo = ($saldo>=0);
return new JsonResponse([
'creditos'=>$creditos,
'debitos'=>$debitos,
'totalCreditos'=>number_format($totalCreditos, 2, ',', '.'),
'totalDebitos'=>number_format($totalDebitos, 2, ',', '.'),
'saldo'=>number_format($saldo, 2, ',', '.'),
'saldoPositivo'=>$saldoPositivo,
'totalLancamentosIndividuais' => number_format($totalLancamentosIndividuais, 2, ',', '.')
], 200);
}
private function getLancamentosPorPedido($pedidoRequest) {
$pagamentosData = [];
$total = 0;
$pagamentos = $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->findBy(['pedido'=>$pedidoRequest]);
foreach ($pagamentos as $pagamento) {
$total +=$pagamento->getValor();
$pagamentosData[] = [
'id' => $pagamento->getId(),
'valor' => number_format($pagamento->getValor(), 2, ',', '.'),
'obs' => $pagamento->getObs(),
'tipo' => $pagamento->getTipo(),
'data' => $pagamento->getPagoAt()->format('d/m/Y'),
];
}
return ['lancamentos'=>$pagamentosData, 'total'=>$total];
}
/**
* @Route("/app-externo/drive/lancamentos/delete", name="lancamento_delete_drive", methods={"POST"})
*/
public function deleteLancamentoDriveAction(Request $request)
{
$data = json_decode($request->getContent(), false);
$lancamento = $this->getDoctrine()->getRepository(LancamentoClienteDrive::class)->find($data->id);
if(!$lancamento instanceof LancamentoClienteDrive) {
return new JsonResponse([], 400);
}
// Deleta os lancamentos individuais
$totalLancamentosIndividuais = $this->getDoctrine()->getRepository(PagamentoPedidoCreditoDebito::class)->findBy(['pedido'=>$lancamento]);
foreach ($totalLancamentosIndividuais as $totalLancamentoIndividual) {
$this->getDoctrine()->getManager()->remove($totalLancamentoIndividual);
$this->getDoctrine()->getManager()->flush();
}
$this->getDoctrine()->getManager()->remove($lancamento);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([], 200);
}
###### DRIVE
/**
* @Route("/app-externo/teste_zap", name="teste-zap", methods={"GET"})
*/
public function testeZapAction(KernelInterface $kernel, BlingService $blingService)
{
// $acoes = [];
// $acoes[] = 'Atualização de produto';
// $acoes[] = 'Atualização de produto';
// $acoes[] = 'Atualização de produto';
// $acoes[] = 'Atualização de produto';
// $acoes[] = 'Atualização de produto';
// if(!$blingService->temRequisicaoDisponivel(count($acoes))){
// exit('Ações não permitidas');
// }
// $blingService->registraRequisicaoBling($acoes);
// exit('Ações cadastradas');
$numeroPedido = 1234;
$messageBody = "Teste de envio de zap\nCom quebra de linha";
$this->sendMensagemViaWhatsapp("img", "5562983281823", $messageBody, 'https://polo.srvtmp.com.br/bg_promocoes/individuais/individual_1.jpeg?v=1704901159', null, null); // Benjamim
exit;
$url = 'https://isp.owenbrasil.com.br/api/global.php';
$toquen = 'Q68XUMRFAANCIQ0UK3HL6KJ5OGATTXBBUDZTG52U';
$numeroTelefone = '5562983281823';
$messageBody = "Teste";
$messageBody = $messageBody . " - #Pollo Móveis#";
$posts = array(
'tipo' => 'img',
'token' => $toquen,
'numero' => $numeroTelefone,
'mensagem'=> $messageBody,
'urlimg' => "https://polo.srvtmp.com.br/bg_promocoes/individuais/individual_1.jpeg?v=1704901159"
);
$posts = array(
'tipo' => 'normal',
'token' => $toquen,
'numero' => $numeroTelefone,
'mensagem'=> $messageBody
);
// // Construa a URL com os parâmetros de consulta
// $url .= '?' . http_build_query($posts);
// $curl_handle = curl_init();
// curl_setopt($curl_handle, CURLOPT_URL, $url);
// curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, TRUE);
// curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
// curl_setopt($curl_handle, CURLOPT_SSL_VERIFYHOST, false);
// curl_setopt($curl_handle, CURLOPT_HTTPGET, true);
// $response = curl_exec($curl_handle);
// $responseJson = json_decode($response);
// print_r($responseJson); exit;
// if($responseJson->statusCode==200){
// exit('Mensagem ID: ' . $responseJson->idMessage);
// } else {
// exit("Mensagem não enviada!");
// }
}
// /**
// * @Route("/app-externo/calcula_tolerancia_entrega", name="calcula_tolerancia_entrega", methods={"GET"})
// */
// public function testeAction(KernelInterface $kernel)
// {
// $dataUltimaMovimentacao = '2023-11-30 18:00:00';
// $dataVerificacaoScript = '2023-12-01 12:00:00';
// echo $this->calcularDiferencaHoras($dataUltimaMovimentacao, $dataVerificacaoScript);
// // Exemplo de uso
// // $dataAceitacao = '2023-11-30 16:00:00';
// // $tolerancia = 4;
// // if ($this->ultrapassouTolerancia($dataAceitacao, $tolerancia)) {
// // echo "Tolerância: $tolerancia<br/>Data aceitação: $dataAceitacao<br/><br/>Pedido ultrapassou a tolerância.\n";
// // } else {
// // echo "Tolerância: $tolerancia<br/>Data aceitação: $dataAceitacao<br/><br/>Pedido dentro da tolerância.\n";
// // }
// exit;
// }
// function calcularDiferencaHoras($dataInicial, $dataFinal) {
// $dataInicio = new \DateTime($dataInicial);
// $dataFim = new \DateTime($dataFinal);
// // Define o horário de início e fim do expediente
// $horarioInicio = 8;
// $horarioFim = 18;
// // Inicializa a diferença total em horas
// $diferencaTotal = 0;
// while ($dataInicio < $dataFim) {
// // Calcula o horário de início e fim para o dia atual
// $inicioDiaAtual = clone $dataInicio;
// $inicioDiaAtual->setTime($horarioInicio, 0, 0);
// $fimDiaAtual = clone $dataInicio;
// $fimDiaAtual->setTime($horarioFim, 0, 0);
// // Calcula a diferença entre o início e o fim do dia, desconsiderando sábados e domingos
// if ($dataInicio->format('N') <= 5) {
// $diferencaDia = min($fimDiaAtual, $dataFim)->getTimestamp() - max($inicioDiaAtual, $dataInicio)->getTimestamp();
// $diferencaDia = max(0, $diferencaDia);
// $diferencaTotal += $diferencaDia;
// }
// // Adiciona um dia completo
// $dataInicio->add(new \DateInterval('P1D'));
// }
// // Converte a diferença total para horas
// $diferencaTotalHoras = $diferencaTotal / 3600;
// return $diferencaTotalHoras;
// }
// function ultrapassouTolerancia($dataAceitacao, $tolerancia) {
// $dataEntrega = new \DateTime($dataAceitacao);
// // Define o horário de início e fim do expediente
// $horarioInicio = 8;
// $horarioFim = 18;
// // Adiciona a tolerância ao horário de aceitação
// $dataEntrega->modify("+$tolerancia hours");
// // Ajusta o horário de início e fim para dias úteis
// $dataEntrega->setTime($horarioInicio, 0, 0);
// $dataFimExpediente = clone $dataEntrega;
// $dataFimExpediente->setTime($horarioFim, 0, 0);
// // Verifica se a entrega ultrapassa o expediente
// if ($dataEntrega > $dataFimExpediente) {
// // Se ultrapassar, ajusta para o próximo dia útil
// $dataEntrega->modify("+$horarioInicio hours");
// }
// var_dump($dataFimExpediente);
// $agora = new \DateTime();
// return $dataEntrega <= $agora;
// }
/**
* @Route("/app-externo/pedidos-nao-cadastrados", name="pedidos_nao_cadastrados", methods={"POST"})
*/
public function pedidosNaoCadastrados(Request $request)
{
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Access-Control-Allow-Headers: Content-Type, Authorization');
header('Access-Control-Allow-Credentials: true');
header('Content-Type: application/json');
//$data = json_decode($request->getContent(), false);
//$pedidos = $data->pedidos;
$pedidos = $request->get('pedidos');
$pedidos = explode(',', $pedidos);
$pedidosNaoCadastrados = [];
$connection = $this->getDoctrine()->getConnection('default');
foreach ($pedidos as $pedido) {
$results = $connection->executeQuery("
SELECT pedido
FROM entrega_pedido
WHERE pedido=$pedido AND deleted_at is null")
->fetchAllAssociative();
if(count($results)==0){
$pedidosNaoCadastrados[]=$pedido;
}
}
echo json_encode($pedidosNaoCadastrados);
exit;
}
public function temAlgumValePendente() {
if(!$this->getIsAdmin()){
return false;
}
$solicitacaoPendnte = $this->getDoctrine()->getRepository(ValeSolicitacao::class)->colaboradorTemValePendente(null, true);
$solicitacaoPendnte = (count($solicitacaoPendnte)) ? true : false;
return $solicitacaoPendnte;
}
/**
* @Route("/app-externo/texte-api", name="texte_api", methods={"GET"})
*/
public function testeApi(KernelInterface $kernel)
{
// $type = "img";
// $numeroTelefone = "5562983281823";
// $messageBody = "Teste de texto com texto";
// $img = "https://polo.srvtmp.com.br/frontend/images/logo.png";
// $nomePdf = null;
// $urlpdf = null;
// // Envia Imagem
// $this->sendMensagemViaWhatsappV2($type, $numeroTelefone, $messageBody, $img, $nomePdf, $urlpdf);
// $type = "text";
// $numeroTelefone = "5562983281823";
// $messageBody = "Teste de texto";
// $img = null;
// $nomePdf = null;
// $urlpdf = null;
// // Envia texto
// $this->sendMensagemViaWhatsappV2($type, $numeroTelefone, $messageBody, $img, $nomePdf, $urlpdf);
exit();
}
/**
* @Route("/app-externo/atualiza-valores-diarios", name="atualiza_valores_diarios", methods={"POST"})
*/
public function atualizaValoresDiarios(KernelInterface $kernel)
{
$application = new Application($kernel);
$application->setAutoExit(false);
$input = new ArrayInput([
'command' => 'app:acoes-pedidos-diario',
]);
// You can use NullOutput() if you don't need the output
$output = new BufferedOutput();
$application->run($input, $output);
// return the output, don't use if you used NullOutput()
$content = $output->fetch();
// return new Response(""), if you used NullOutput()
return new Response($content);
}
/**
* @Route("/app-externo/relatorios-acompanhamento-pedidos", name="relatorios_acompanhamentos_pedidos", methods={"POST"})
*/
public function getRelatorioAcompanhamentosPedidos(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedidos = [];
$pedidosCodigo = [];
$tipo = $data->dados->tipo; // motorista, separadores, vendedor
$usuarioID = $data->dados->id_user;
$status = $data->dados->status;
$dataInicio = $data->dataInicio;
$dataFim = $data->dataFim;
$user = $this->getDoctrine()->getRepository(User::class)->find($usuarioID);
if($tipo=='motorista') {
$pedidos = $this->getTotalPedidosPorUsuarioEstatus($user,$status,'colaboradorUser', '', $dataInicio, $dataFim, true);
} else if($tipo=='separador') {
// MUDAR QUERY PARA LIKE
//$pedidos = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','separador', $user->getEmail(), $dataInicio, $dataFim, true);
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoSeparador($user->getEmail(), true, $dataInicio, $dataFim);
} else if($tipo=='vendedor') {
$pedidos = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','vendedor_pedidos', $user->getEmail(), $dataInicio, $dataFim, true, $data->dados->periodo);
} else if($tipo=='auxiliar') {
$pedidos = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','auxiliares', $user->getEmail(), $dataInicio, $dataFim, true);
}
foreach ($pedidos as $pedido) {
$pedidosCodigo[] = (empty($pedido->getPedido())) ? $pedido->getNotaFiscal() : $pedido->getPedido();
}
$oss = $this->getDoctrine()->getRepository(OrdemServico::class)->getOsNaData($dataInicio, $dataFim, $user);
foreach ($oss as $os) {
$pedidosCodigo[] = 'OS: ' . $os->getNumero();
}
echo implode('-',$pedidosCodigo);
exit;
}
private function getTotalOsAceitaPorUsuario($user, $dataInicio, $dataFim) {
// $user = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$userEmail]);
// if(!$user instanceof User){
// return 0;
// }
$obss = $this->getDoctrine()->getRepository(OrdemServico::class)->getOsNaData($dataInicio, $dataFim, $user);
//echo ($userEmail . ' - TOTAL: ' . count($obss));
return count($obss);
}
/**
* @Route("/app-externo/relatorios-acompanhamento", name="relatorios_acompanhamentos", methods={"GET"})
*/
public function getRelatorioAcompanhamentos(Request $request): Response
{
$dados = [
'motoristas' => [],
'separadores' => [],
'vendedores' => [],
];
//return new JsonResponse($dados, 200);
$users = $this->getDoctrine()->getRepository(User::class)->findAll();
$dataInicio = $request->get('dataInicio');
$dataFim = $request->get('dataFim');
foreach ($users as $user) {
if(in_array('ROLE_ENTREGADOR', $user->getRoles())) {
if($user->getNome()=='Richardy'){continue;}
$pedidosAceitos = $this->getTotalPedidosPorUsuarioEstatus($user,'aceito','colaboradorUser', '', $dataInicio, $dataFim);
$pedidosTransito = 0; //$this->getTotalPedidosPorUsuarioEstatus($user,'transito','colaboradorUser', '', $dataInicio, $dataFim);
$pedidosEntregue = 0; //$this->getTotalPedidosPorUsuarioEstatus($user,'entregue','colaboradorUser', '', $dataInicio, $dataFim);
$pedidosBaixado = 0; //$this->getTotalPedidosPorUsuarioEstatus($user,'baixado','colaboradorUser', '', $dataInicio, $dataFim);
$totalOs = $this->getTotalOsAceitaPorUsuario($user, $dataInicio, $dataFim);
$pedidosAceitos +=$totalOs;
$total = $pedidosAceitos+$pedidosTransito+$pedidosEntregue+$pedidosBaixado;
$dados['motoristas'][] = [
'nome' => $user->getNome(),
'id' => $user->getId(),
'aceito' => $pedidosAceitos,
'transito' => $pedidosTransito,
'entregue' => $pedidosEntregue,
'baixado' => $pedidosBaixado,
'total' => $total
];
}
if(in_array('ROLE_SEPARADOR', $user->getRoles())) {
//if($user->getNome()=='Richardy'){continue;}
$totalAceitos = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'aceito','separador', $user->getEmail(), $dataInicio, $dataFim);
$totalPronto = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'pronto','separador', $user->getEmail(), $dataInicio, $dataFim);
$totalbaixados = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'baixado','separador', $user->getEmail(), $dataInicio, $dataFim);
$dados['separadores'][] = [
'nome' => $user->getNome(),
'id' => $user->getId(),
'aceito' => $totalAceitos,
'pronto' => $totalPronto,
'baixado' => $totalbaixados
];
}
if(in_array('ROLE_VENDEDOR', $user->getRoles())) {
if($user->getNome()=='Junior'){continue;}
$totalDia = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'dia','vendedor', $user->getEmail(), $dataInicio, $dataFim);
$totalMes = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'mes','vendedor', $user->getEmail(), $dataInicio, $dataFim);
$dados['vendedores'][] = [
'nome' => $user->getNome(),
'id' => $user->getId(),
'dia' => number_format($totalDia, 2, ',', '.'),
'mes' => number_format($totalMes, 2, ',', '.'),
'total' => $totalMes
];
}
if(in_array('ROLE_AUX_ENTREGADOR', $user->getRoles())) {
$totalDia = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'dia','auxiliares', $user->getEmail(), $dataInicio, $dataFim);
$totalMes = $this->getTotalPedidosPorUsuarioEstatus($user->getNome(),'mes','auxiliares', $user->getEmail(), $dataInicio, $dataFim);
// Pegar total de os aceita
$totalOs = $this->getTotalOsAceitaPorUsuario($user, $dataInicio, $dataFim);
$totalMes += $totalOs;
$dados['auxiliares'][] = [
'nome' => $user->getNome(),
'id' => $user->getId(),
'dia' => number_format($totalDia, 2, ',', '.'),
'mes' => number_format($totalMes, 2, ',', '.'),
'total' => $totalMes
];
}
}
$totalAceitos = $this->getTotalPedidosPorUsuarioEstatus('João Marcos', 'aceito', 'separador', 'joao_marcos', $dataInicio, $dataFim);
$totalPronto = $this->getTotalPedidosPorUsuarioEstatus('João Marcos', 'pronto', 'separador', 'joao_marcos', $dataInicio, $dataFim);
$totalbaixados = $this->getTotalPedidosPorUsuarioEstatus('João Marcos', 'baixado', 'separador', 'joao_marcos', $dataInicio, $dataFim);
$dados['separadores'][] = [
'nome' => 'João Marcos',
'id' => 12,
'aceito' => $totalAceitos,
'pronto' => $totalPronto,
'baixado' => $totalbaixados
];
$totalDia = $this->getTotalPedidosPorUsuarioEstatus('Richardy','dia','vendedor','richardy', $dataInicio, $dataFim);
$totalMes = $this->getTotalPedidosPorUsuarioEstatus('Richardy','mes','vendedor','richardy', $dataInicio, $dataFim);
$dados['vendedores'][] = [
'nome' => 'Richardy',
'id' => 15,
'dia' => number_format($totalDia, 2, ',', '.'),
'mes' => number_format($totalMes, 2, ',', '.'),
'total' => $totalMes
];
$totalAceitos = $this->getTotalPedidosPorUsuarioEstatus('Richardy', 'aceito', 'separador', 'richardy', $dataInicio, $dataFim);
$totalPronto = $this->getTotalPedidosPorUsuarioEstatus('Richardy', 'pronto', 'separador', 'richardy', $dataInicio, $dataFim);
$totalbaixados = $this->getTotalPedidosPorUsuarioEstatus('Richardy', 'baixado', 'separador', 'richardy', $dataInicio, $dataFim);
$dados['separadores'][] = [
'nome' => 'Richardy',
'id' => 15,
'aceito' => $totalAceitos,
'pronto' => $totalPronto,
'baixado' => $totalbaixados
];
$totalDiaOutros = $this->getTotalPedidosPorUsuarioEstatus('outros','dia','vendedor','outros', $dataInicio, $dataFim);
$totalMesOutros = $this->getTotalPedidosPorUsuarioEstatus('outros','mes','vendedor','outros', $dataInicio, $dataFim);
$dados['vendedores'][] = [
'nome' => 'Outros',
'id' => 16,
'dia' => number_format($totalDiaOutros, 2, ',', '.'),
'mes' => number_format($totalMesOutros, 2, ',', '.'),
'total' => $totalMesOutros
];
usort($dados['vendedores'], function($a, $b) {
return $b['total'] - $a['total'];
});
usort($dados['separadores'], function($a, $b) {
return $b['aceito'] - $a['aceito'];
});
usort($dados['motoristas'], function($a, $b) {
return $b['total'] - $a['total'];
});
usort($dados['auxiliares'], function($a, $b) {
return $b['total'] - $a['total'];
});
$dados['maior_motorista'] = $dados['motoristas'][0]['total'];
$dados['maior_separador'] = $dados['separadores'][0]['aceito'];
$dados['maior_vendedor'] = $dados['vendedores'][0]['total'];
$dados['maior_auxiliar'] = $dados['auxiliares'][0]['total'];
$dados['montagens'] = $this->getMontagensRelatorio();
usort($dados['montagens'], function($a, $b) {
return $b['pedido'] - $a['pedido'];
});
return new JsonResponse($dados, 200);
}
private function pedidoFinalizado($montagensFinalizadas, $pedidoNumero) {
$data = '';
foreach ($montagensFinalizadas as $pedido) {
if($pedido['pedido']==$pedidoNumero){
$data = $pedido['data'];
}
}
return $data;
}
function extrairNumero($s) {
if (preg_match('/\d+/', $s, $matches)) {
return intval($matches[0]);
} else {
return null;
}
}
private function getMontagensRelatorio() {
$dados = [];
$montagensFinalizadas = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('finalizados');
$montagensFinalizadasData = [];
foreach ($montagensFinalizadas as $pedido) {
$pedidoReplace = $this->extrairNumero($pedido->getPedido());
$montagensFinalizadasData[] = [
'id' => $pedido->getId(),
'pedido' => $pedidoReplace,
'montador' => 'Finalizados',
'cor' => 'blue',
'data' => ($pedido->getPedidoMontandoMontagemFinalizada() instanceof \DateTime) ? $pedido->getPedidoMontandoMontagemFinalizada()->format('d/m/Y H:i') : ''
];
}
$montagensRonald = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('Ronald');
foreach ($montagensRonald as $pedido) {
$data = $this->pedidoFinalizado($montagensFinalizadasData,$pedido->getPedido());
$cor = ($data!='') ? 'blue' : 'black';
$pedidoReplace = $this->extrairNumero($pedido->getPedido());
$dados[] = [
'id' => $pedido->getId(),
'pedido' => $pedidoReplace,
'montador' => 'Ronald',
'cor' => $cor,
'data' => ($pedido->getPedidoMontandoRonald() instanceof \DateTime) ? $pedido->getPedidoMontandoRonald()->format('d/m/Y H:i') : '',
'finalizado' => $data
];
}
$montagensFabio = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('Fabio');
foreach ($montagensFabio as $pedido) {
$data = $this->pedidoFinalizado($montagensFinalizadasData,$pedido->getPedido());
$cor = ($data!='') ? 'blue' : 'black';
$pedidoReplace = str_replace('-Assistência','', $pedido->getPedido());
$dados[] = [
'id' => $pedido->getId(),
'pedido' => $pedidoReplace,
'montador' => 'Fábio',
'cor' => $cor,
'data' => ($pedido->getPedidoMontandoFabio() instanceof \DateTime) ? $pedido->getPedidoMontandoFabio()->format('d/m/Y H:i') : '',
'finalizado' => $data
];
}
$montagensRian = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosMonstagens('Rian');
foreach ($montagensRian as $pedido) {
$data = $this->pedidoFinalizado($montagensFinalizadasData,$pedido->getPedido());
$cor = ($data!='') ? 'blue' : 'black';
$pedidoReplace = str_replace('-Assistência','', $pedido->getPedido());
$dados[] = [
'id' => $pedido->getId(),
'pedido' => $pedidoReplace,
'montador' => 'Rian',
'cor' => $cor,
'data' => ($pedido->getPedidoMontandoRian() instanceof \DateTime) ? $pedido->getPedidoMontandoRian()->format('d/m/Y H:i') : '',
'finalizado' => $data
];
}
return $dados;
}
private function getTotalPedidosPorUsuarioEstatus($user, $status, $tipoColaborador, $userEmail='', $dataInicio, $dataFim, $devolveEntidades=false, $periodo=null) {
if($tipoColaborador=='colaboradorUser') {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosParaRelatorioDesempenho($user, $status, $tipoColaborador, $userEmail, $dataInicio, $dataFim);
} else if($tipoColaborador=='separador') {
// MUDAR PARA LIKE TAMBEM
//$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosParaRelatorioDesempenho($user, $status, $tipoColaborador, $userEmail, $dataInicio, $dataFim);
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoSeparador($user, true, $dataInicio, $dataFim);
} else if($tipoColaborador=='outros') {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoOutros($user, $status);
$pedidos = [];
} else if($tipoColaborador=='vendedor') {
// $jsonFile = ($status=='dia') ? '/www/wwwroot/gestor.moveispollo.com.br/db_local_today.json' : '/www/wwwroot/gestor.moveispollo.com.br/db_local.json';
// $jsonData = file_get_contents($jsonFile);
// $data = json_decode($jsonData, true);
// return $data[$user];
$usuarios = [
'nicholas' => 0,
'guilherme' => 0,
'willian' => 0,
'iury' => 0,
'richardy' => 0,
'eduardo' => 0,
'outros' => 0,
];
$usuariosResult = [
'total' => 0,
'nicholas' => 0,
'guilherme' => 0,
'willian' => 0,
'iury' => 0,
'richardy' => 0,
'eduardo' => 0,
'outros' => 0,
];
$total = 0;
$dia = ($status=='dia') ? true : false;
foreach ($usuarios as $key => $value){
$usuarioTotal = $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtual($key,$dia);
$usuariosResult[$key] = $usuarioTotal;
}
$usuariosResult['total'] = $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtual($userEmail,true);
if(!isset($usuariosResult[$userEmail])){
return 0;
}
return $usuariosResult[$userEmail];
} else if($tipoColaborador=='vendedor_pedidos') {
switch($userEmail) {
case 'nicholas':
$user = 'NICHOLLAS';
break;
case 'guilherme':
$user = 'Guilherme Leão';
break;
case 'willian':
$user = 'WILLIAN LOPES';
break;
case 'iury':
$user = 'IURY SOUSA';
break;
case 'joao_marcos':
$user = 'João Marcos';
break;
case 'richardy':
$user = 'Richardy';
break;
case 'eduardo':
$user = 'Eduardo Gabriel';
break;
case 'bruno@moveispollo.com.br':
$user = 'Bruno Oliveira';
break;
}
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)
->getPedidosParaRelatorioDesempenho($user, $status, 'vendedor', $userEmail, $dataInicio, $dataFim, $periodo);
} else if($tipoColaborador=='auxiliares') {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)
->getPedidosParaRelatorioDesempenho($user, $status, 'auxiliares', $userEmail, $dataInicio, $dataFim);
}
if($devolveEntidades){ return $pedidos; }
return count($pedidos);
}
/**
* @Route("/app-externo/produtos-pendentes-nao-aceitos-pela-pollo", name="getTotalPedidosNaoAceitosComEntregaPelaPollo", methods={"GET"})
*/
public function getTotalPedidosNaoAceitosComEntregaPelaPolloAction(Request $request): Response
{
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getTotalPedidosNaoAceitosComEntregaPelaPollo();
$codigos = [];
foreach ($pedidos as $pedido){
$codigos[] = ($pedido->getPedido()) ? $pedido->getPedido() : $pedido->getNotaFiscal();
}
return new JsonResponse(['total'=>count($pedidos), 'codigos'=>join(' - ', $codigos)], 200);
}
/**
* @Route("/app-externo/busca-avancada", name="busca_avancada", methods={"POST"})
*/
public function buscaAvancada(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedidosData = [];
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilterAdvanced($data);
foreach ($pedidos as $pedido) {
$pedidoNumero = empty($pedido->getPedido()) ? $pedido->getNotaFiscal() : $pedido->getPedido();
$pedidosData[] = ['id'=>$pedido->getId(), 'pedido'=>$pedidoNumero, 'nome' => $pedido->getContato()];
}
return new JsonResponse($pedidosData, 200);
}
############# CHAT
/**
* @Route("/app-externo/chat/lida", name="mensagem_lida", methods={"POST"})
*/
public function lerMensagemChat(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$user = $this->getUser();
$mensageEntity = $this->getDoctrine()->getRepository(MensagemMural::class)->find($data->mensagem);
if($mensageEntity->getIsTodosLer()){
if($mensageEntity->getDestinatarioTodos()=='' || $mensageEntity->getDestinatarioTodos()==null){
$mensageEntity->setDestinatarioTodos($user->getEmail());
} else {
$todosLido = explode(',', $mensageEntity->getDestinatarioTodos());
$todosLido[] = $user->getEmail();
$todosLido = implode(',',$todosLido);
$mensageEntity->setDestinatarioTodos($todosLido);
}
} else {
if($mensageEntity->getDestinatario()->getId()!=$user->getId()){
return new JsonResponse([], 400);
}
$mensageEntity->setIsLida(true);
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->getAllMensagensChat(), 200);
}
/**
* @Route("/app-externo/cadastro/coleta", name="cadastro_coleta", methods={"POST"})
*/
public function addColeta(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$destinatario = $this->getDoctrine()->getRepository(User::class)->find($data->destinatario);
$mensagem = (new MensagemColeta)
->setTexto($data->mensagem)
->setDestinatario($destinatario)
->setCreatedAt(new \DateTime())
->setIsLida(false)
->setPedido('nenhum');
$this->getDoctrine()->getManager()->persist($mensagem);
$this->getDoctrine()->getManager()->flush();
$messageBody = "Solicitação de coleta de mercadoria:\\n\\n" . $data->mensagem;
$this->sendMensagemViaWhatsapp("text", $destinatario->getTelefone(), $messageBody, null, null, null);
//$this->sendMensagemViaWhatsapp("text", '5562991089053', $messageBody, null, null, null);
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/usuarios/coleta/ler", name="ler_mensagem_coleta", methods={"POST"})
*/
public function lerMensagemColeta(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$mensagem = $this->getDoctrine()->getRepository(MensagemColeta::class)->find($data->id);
if($mensagem->getDestinatario()->getId() != $this->getUser()->getId()){
return new JsonResponse([], 401);
}
$mensagem->setIsLida(true);
$this->getDoctrine()->getManager()->flush();
$messageBody = "Mercadoria coletada com sucesso - Separador: *".$this->getUser()->getNome()."*:\\n\\n" . $mensagem->getTexto();
$this->sendMensagemViaWhatsapp("text", '5562991089053', $messageBody, null, null, null);
return new JsonResponse([], 200);
}
/**
* @Route("/app-externo/usuarios/coleta/lista", name="lista_mensagens_coleta", methods={"GET"})
*/
public function mensagensColeta(Request $request): Response
{
$mensagensData = [];
if($this->getIsAdmin()) {
$mensagens = $this->getDoctrine()->getRepository(MensagemColeta::class)->findBy([],['isLida'=>'ASC', 'createdAt'=>'DESC']);
} else {
$mensagens = $this->getDoctrine()->getRepository(MensagemColeta::class)->findBy(['destinatario'=>$this->getUser()], ['isLida'=>'ASC', 'createdAt'=>'DESC']);
}
$haveIsNaoLida = false;
foreach ($mensagens as $mensagem) {
if(!$mensagem->getIsLida()){
$haveIsNaoLida = true;
}
$mensagensData[] = [
'id' => $mensagem->getId(),
'destinatario' => ($mensagem->getDestinatario()) ? $mensagem->getDestinatario()->getNome() : 'não informado',
'mensagem' => $mensagem->getTexto(),
'pedido' => $mensagem->getPedido(),
'isLida' => $mensagem->getIsLida(),
'data' => $mensagem->getCreatedAt()->format('d/m/Y H:i')
];
}
return new JsonResponse(['mensagens'=>$mensagensData, 'haveIsNaoLida'=>$haveIsNaoLida], 200);
}
/**
* @Route("/app-externo/usuarios/coleta", name="list_usuarios_coleta", methods={"GET"})
*/
public function usersColeta(Request $request): Response
{
$dataRes = [];
$userLogado = $this->getUser();
$users = $this->getDoctrine()->getRepository(User::class)->findAll();
foreach ($users as $user) {
if($user->getId()!=$userLogado->getId() && in_array('ROLE_ENTREGADOR', $user->getRoles())){
$dataRes[] = [
'value' => $user->getId(),
'text' => $user->getNome(),
];
}
}
return new JsonResponse($dataRes, 200);
}
/**
* @Route("/app-externo/chat/usuarios", name="list_usuarios_chat", methods={"GET"})
*/
public function usersChat(Request $request): Response
{
$dataRes = [];
$dataRes[] = [
'value' => 'todos',
'text' => 'Todos',
];
$dataRes[] = [
'value' => 'todos_read',
'text' => 'Todos com Leitura',
];
$userLogado = $this->getUser();
$users = $this->getDoctrine()->getRepository(User::class)->findAll();
foreach ($users as $user) {
if($user->getId()!=$userLogado->getId()){
$dataRes[] = [
'value' => $user->getEmail(),
'text' => $user->getNome(),
];
}
}
return new JsonResponse($dataRes, 200);
}
/**
* @Route("/app-externo/chat/post", name="post_mensagem", methods={"POST"})
*/
public function addMensagemChat(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$user = $this->getUser();
if(empty($data->mensagem)){
return new JsonResponse($this->getPedidosNaoLidos(), 400);
}
$todosLer = ($data->destinatario=='todos_read') ? true : false;
$mensagem = (new MensagemMural())
->setMensagem($data->mensagem)
->setUsuario($user)
->setCreatedAt(new \DateTime('now'))
->setIsPrivate($data->isPrivado)
->setIsTodosLer($todosLer)
;
if($data->destinatario!='todos' && $data->destinatario!='todos_read'){
$userDestinatario = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->destinatario]);
$mensagem->setDestinatario($userDestinatario);
$messageBody = "Nova mensagem no mural do app:\n\n" . $data->mensagem;
$this->sendMensagemViaWhatsapp("text", $userDestinatario->getTelefone(), $messageBody, null, null, null);
}
if($data->destinatario=='todos_read'){
$userDestinatarios = $this->getDoctrine()->getRepository(User::class)->findBy(['zapIsHabilitado'=>true]);
$remetente = $user->getNome();
foreach ($userDestinatarios as $userDestinatario){
if($userDestinatario->getEmail()!=$user->getEmail()){
$messageBody = "Nova mensagem no mural do app:\n\nRemetente: $remetente\n\n" . $data->mensagem;
$this->sendMensagemViaWhatsapp("text", $userDestinatario->getTelefone(), $messageBody, null, null, null);
}
}
}
if($data->isPrivado) {
$remetente = $user->getNome();
$messageBody = "Nova mensagem privada no mural do app:\n\n*Remetente:* $remetente\n\n" . $data->mensagem;
//$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // Benjamim
//$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
$this->sendMensagemViaWhatsapp("text", "556291089053", $messageBody, null, null, null); // Bruno
//$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
}
$this->getDoctrine()->getManager()->persist($mensagem);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->getAllMensagensChat(), 200);
}
/**
* @Route("/app-externo/chat/list/all", name="list_all", methods={"GET"})
*/
public function listAllMensagemChat(Request $request): Response
{
return new JsonResponse($this->getAllMensagensChat(), 200);
}
/**
* @Route("/app-externo/chat/delete", name="delete_mensagem_chat", methods={"POST"})
*/
public function deleteMensagemChat(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$user = $this->getUser();
$mensageEntity = $this->getDoctrine()->getRepository(MensagemMural::class)->find($data->id);
if(!$this->getIsAdmin() && $mensageEntity->getUsuario()->getId() != $user->getId()){
return new JsonResponse([], 400);
}
$this->getDoctrine()->getManager()->remove($mensageEntity);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->getAllMensagensChat(), 200);
}
private function getAllMensagensChat() {
$mensagensData = [];
$user = $this->getUser();
$mensagensEntity = $this->getDoctrine()->getRepository(MensagemMural::class)->findBy([], ['createdAt'=>'DESC']);
if(!$this->getIsAdmin()) {
$mensagensEntity = $this->getDoctrine()->getRepository(MensagemMural::class)->findBy(['isPrivate'=>false], ['createdAt'=>'DESC']);
}
foreach($mensagensEntity as $mensagemItem) {
$nome = '';
if($mensagemItem->getUsuario() instanceof User && $user instanceof User){
$nome = ($mensagemItem->getUsuario()->getId() == $user->getId()) ? 'Eu' : $mensagemItem->getUsuario()->getNome();
}
$isLida = true;
$souDestinatario = false;
// Tem destinatario
if($mensagemItem->getDestinatario()!=null && $mensagemItem->getDestinatario()!=''){
// Destinatário não é o usuário logado
if($mensagemItem->getDestinatario()->getId()==$user->getId()){
$isLida = $mensagemItem->getIsLida();
$souDestinatario = true;
$mensagensData[] = [
'id' => $mensagemItem->getId(),
'mensagem' => $mensagemItem->getMensagem(),
'data' => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
'user' => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
'isPrivate' => $mensagemItem->getIsPrivate(),
'isOwner' => ($mensagemItem->getUsuario()->getId() == $user->getId()),
'isLida' => $isLida,
'lidaOriginal' => $mensagemItem->getIsLida(), // Para admin controlar
'isMim' => $souDestinatario,
'destinatario' => true,
'destNome' => $mensagemItem->getDestinatario()->getNome(),
'todosLer' => false,
'souRemetente' => ($nome=='Eu') ? true : false,
'quemLeu' => $mensagemItem->getDestinatarioTodos()
];
} else {
if($this->getIsAdmin()){
$isLida = $mensagemItem->getIsLida();
$souDestinatario = false;
$mensagensData[] = [
'id' => $mensagemItem->getId(),
'mensagem' => $mensagemItem->getMensagem(),
'data' => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
'user' => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
'isPrivate' => $mensagemItem->getIsPrivate(),
'isOwner' => ($mensagemItem->getUsuario()->getId() == $user->getId()),
'isLida' => $isLida,
'lidaOriginal' => $mensagemItem->getIsLida(), // Para admin controlar
'isMim' => $souDestinatario,
'destinatario' => true,
'destNome' => '',
'todosLer' => false,
'souRemetente' => ($nome=='Eu') ? true : false,
'quemLeu' => $mensagemItem->getDestinatarioTodos()
];
}
}
} else {
// Mensagem para todos lerem
if($mensagemItem->getIsTodosLer()){
$isLida = (strpos($mensagemItem->getDestinatarioTodos(), $user->getEmail())===false) ? false : true;
$lidaOriginal = true;
$userDestinatarios = $this->getDoctrine()->getRepository(User::class)->findBy(['zapIsHabilitado'=>true]);
foreach ($userDestinatarios as $userDestinatario){
if($userDestinatario->getId()!=$user->getId()){
$usuarioNaoLocalizado = $user->getEmail();
// Este usuário não consta na lista
if(!strpos($mensagemItem->getDestinatarioTodos(), $user->getEmail())){
$lidaOriginal = false;
break;
}
}
}
$souDestinatario = false;
$mensagensData[] = [
'id' => $mensagemItem->getId(),
'mensagem' => $mensagemItem->getMensagem(),
'data' => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
'user' => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
'isPrivate' => $mensagemItem->getIsPrivate(),
'isOwner' => ($mensagemItem->getUsuario()->getId() == $user->getId()),
'isLida' => $isLida,
'lidaOriginal' => $lidaOriginal, // Para admin controlar
'isMim' => $souDestinatario,
'destinatario' => false,
'destNome' => '',
'todosLer' => true,
'souRemetente' => ($nome=='Eu') ? true : false,
'quemLeu' => $mensagemItem->getDestinatarioTodos()
];
} else {
$isOwner = false;
if($user instanceof User){
$isOwner = ($mensagemItem->getUsuario()->getId() == $user->getId());
}
$souDestinatario = false;
$mensagensData[] = [
'id' => $mensagemItem->getId(),
'mensagem' => $mensagemItem->getMensagem(),
'data' => $mensagemItem->getCreatedAt()->format('d/m/Y H:i'),
'user' => ['email'=>$mensagemItem->getUsuario()->getEmail(), 'nome'=>$nome],
'isPrivate' => $mensagemItem->getIsPrivate(),
'isOwner' => $isOwner,
'isLida' => $isLida,
'lidaOriginal' => $mensagemItem->getIsLida(), // Para admin controlar
'isMim' => $souDestinatario,
'destinatario' => false,
'destNome' => '',
'todosLer' => false,
'souRemetente' => ($nome=='Eu') ? true : false,
'quemLeu' => $mensagemItem->getDestinatarioTodos()
];
}
}
}
return array_slice($mensagensData, 0, 30);
}
############# CHAT
private function getFaturamentoAtual() {
// $faturamentoAtual = 0;
// $jsonFile = '/www/wwwroot/gestor.moveispollo.com.br/db_local.json';
// $jsonData = file_get_contents($jsonFile);
// $data = json_decode($jsonData, true);
// $faturamentoAtual = $data['total'];
$total = $this->getDoctrine()->getRepository(PedidoAcumulado::class)->findMesAtual();
return $total;
}
/**
* @Route("/app-externo-socket", name="app_externo_socket")
*/
public function indexSocket(Request $request): Response
{
return $this->render('app_externo/index-socket.html.twig');
}
/**
* @Route("/app-externo", name="app_externo")
*/
public function index(Request $request): Response
{
$abrePedidoParaCadastro = 'false';
if($request->get('add_card')){
$abrePedidoParaCadastro = 'true';
}
$pedidosAgendados = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidosAgendados();
$pedidosAgendadosData = [];
foreach ($pedidosAgendados as $pedidoAgendado) {
if($pedidoAgendado->getMeioEntrega()=='Pela Pollo Móveis' || $pedidoAgendado->getMeioEntrega()=='Viagem pela Pollo Móveis'){
$pedidosAgendadosData[] = $pedidoAgendado->getDataEntrega()->format('d/m/y');
}
}
$hoje = new \DateTime();
// Conta o número de ocorrências de cada data
$contagem = array_count_values($pedidosAgendadosData);
// Filtra as datas que aparecem mais de três vezes
$datas_repetidas = array_filter($contagem, function($valor) {
$hoje = new \DateTime();
return $valor > $this->getTotalPedidosDia($hoje);
});
// Extrai as chaves do array resultante
$datas_mais_de_3_vezes = array_keys($datas_repetidas);
// Adicione aspas simples a cada data no array PHP
$datas_desativadas_array = array_map(function($data) {
return "'" . trim($data) . "'";
}, $datas_mais_de_3_vezes);
// Converta o array PHP de volta para uma string separada por vírgulas
$datas_desativadas_string = implode(',', $datas_desativadas_array);
$ultimoDiaMes = clone $hoje;
$ultimoDiaMes->modify('first day of next month');
$ultimoDiaMes->modify('-1 day');
return $this->render('app_externo/index-v2.html.twig', [
'controller_name' => 'AppExternoController',
'usario' => $this->getUser()->getEmail(),
'isAdmin' => $this->getIsAdmin(),
'isEntregador' => $this->getIsEntregador(),
'isEntregadorAux' => $this->getIsEntregadorAux(),
'isVendedor' => $this->getIsVendedor(),
'isSeparador' => $this->getIsSeparador(),
'menuContextoCard' => $this->getMenuContextoCard(),
'dataHoje' => $hoje->format('Y-m-d'),
// 'faturamentoAtual' => __DIR__,
'faturamentoAtual' => number_format($this->getFaturamentoAtual(), 2, ',', '.'),
'abreNovoPedido' => $abrePedidoParaCadastro,
'pedidoNovoParaAdd' => $request->get('add_card'),
'temAlgumValePendente' => $this->temAlgumValePendente(),
'primeiro_dia_mes' => $hoje->format('Y') . '-'.$hoje->format('m').'-01',
'ultimo_dia_mes' => $ultimoDiaMes->format('Y-m-d'),
'datas_pedidos_agendados' => $datas_desativadas_string,
'total_pedidos_liberados_hoje' => 10,
'pode_abrir_modal_pedidos_pendentes_cadastro' => true
]);
}
/**
* @Route("/app-externo/periodos-disponiveis-entrega", name="app_externo_pedidos_disponiveis_entrega", methods={"POST"})
*/
public function getPeriodosDisponiveisEntregaNaData(Request $request): Response
{
$data = json_decode($request->getContent(), false);
if(!isset($data->data)){
return new JsonResponse([
['value'=>'De Manhã', 'text'=>'De Manhã'],
['value'=>'À tarde', 'text'=>'À tarde'],
['value'=>'Qualquer horário', 'text'=>'Qualquer horário'],
], 200);
}
if($data->data=='' || $data->data=='Não informado'){
return new JsonResponse([
['value'=>'De Manhã', 'text'=>'De Manhã'],
['value'=>'À tarde', 'text'=>'À tarde'],
['value'=>'Qualquer horário', 'text'=>'Qualquer horário'],
], 200);
}
$date = \DateTime::createFromFormat('d/m/Y', $data->data);
$hoje = new \DateTime('now');
$dataInicio = $date->format('Y-m-d');
$pedidosAgendados = $this->getDoctrine()
->getRepository(EntregaPedido::class)
->getPedidosAgendadosNaData($dataInicio, $dataInicio, null);
$totalPedidosAgendadosSemViagem = 0;
foreach ($pedidosAgendados as $pedidoAgendado) {
if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
$totalPedidosAgendadosSemViagem++;
}
}
$totalPedidosManha = 0;
$totalPedidosTarde = 0;
$totalPedidosQualquerHorario = 0;
$totalPedidosDia = $this->getTotalPedidosDia($date); // 24 pedidos por dia
$totalPedidosNaDataManha = $this->getDoctrine()->getRepository(EntregaPedido::class)
->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), 'De Manhã');
$totalPedidosNaDataManha = count($totalPedidosNaDataManha);
$totalPedidosNaDataManha = ($totalPedidosDia/2) - $totalPedidosNaDataManha;
$totalPedidosNaDataTarde = $this->getDoctrine()->getRepository(EntregaPedido::class)
->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), 'À tarde');
$totalPedidosNaDataTarde = count($totalPedidosNaDataTarde);
$totalPedidosNaDataTarde = ($totalPedidosDia/2) - $totalPedidosNaDataTarde;
$totalPedidosNaDataQualquerHorario = $this->getDoctrine()->getRepository(EntregaPedido::class)
->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), 'Qualquer horário');
$totalPedidosNaDataQualquerHorarioTotal = count($totalPedidosNaDataQualquerHorario);
$totalPedidosNaDataQualquerHorario = ($totalPedidosDia-($totalPedidosNaDataManha+$totalPedidosNaDataTarde));
$totalPedidosNaDataQualquerHorario = $totalPedidosNaDataQualquerHorario+$totalPedidosNaDataQualquerHorarioTotal;
$totalPedidosNaDataQualquerHorario = $totalPedidosDia-$totalPedidosNaDataQualquerHorario;
$periodosNovo = [];
if(ceil($totalPedidosNaDataManha)>0) {
$periodosNovo[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.ceil($totalPedidosNaDataManha).')'];
} else {
$periodosNovo[] = ['value'=>'lotado', 'text'=>'De Manhã('.ceil($totalPedidosNaDataManha).')'];
}
if(ceil($totalPedidosNaDataTarde)>0) {
$periodosNovo[] = ['value'=>'À Tarde', 'text'=>'À Tarde('.ceil($totalPedidosNaDataTarde).')'];
} else {
$periodosNovo[] = ['value'=>'lotado', 'text'=>'À Tarde('.ceil($totalPedidosNaDataTarde).')'];
}
// if(ceil($totalPedidosNaDataQualquerHorario)>0){
// $periodosNovo[] = ['value'=>'Qualquer horário', 'text'=>'Qualquer horário('.ceil($totalPedidosNaDataQualquerHorario).')'];
// } else {
// $periodosNovo[] = ['value'=>'lotado', 'text'=>'Qualquer horário('.ceil($totalPedidosNaDataQualquerHorario).')'];
// }
// echo "Manha: $totalPedidosNaDataManha - Tarde: $totalPedidosNaDataTarde - Qualquer: $totalPedidosNaDataQualquerHorario - Por dia: $totalPedidosDia";
// exit;
$totalPedidosNaData = $totalPedidosAgendadosSemViagem; // 10 pedidos
$pedidosManha = [];
$pedidosTarde = [];
$pedidosNumeros = [];
foreach ($pedidosAgendados as $pedidoAgendado) {
// verifica se este pedido está com data de entrega anterior a hoje
if($pedidoAgendado->getEntregarAt() instanceof \DateTime){
if($dataInicio > $pedidoAgendado->getEntregarAt()->format('Y-m-d')){
continue;
}
}
$pedidosNumeros[] = ($pedidoAgendado->getPedido()!='') ? $pedidoAgendado->getPedido() : $pedidoAgendado->getNotaFiscal();
if($pedidoAgendado->getPeriodoEntrega()=='Qualquer horário'){
//if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
$totalPedidosQualquerHorario++;
// }
} else if($pedidoAgendado->getPeriodoEntrega()=='De Manhã') {
//if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
$totalPedidosManha++;
//}
$pedidosManha[] = ($pedidoAgendado->getPedido()!='' && $pedidoAgendado->getPedido()!=null) ? $pedidoAgendado->getPedido() : $pedidoAgendado->getNotaFiscal();
} else if($pedidoAgendado->getPeriodoEntrega()=='À tarde') {
//if($pedidoAgendado->getMeioEntrega()!='Viagem pela Pollo Móveis'){
$totalPedidosTarde++;
//}
$pedidosTarde[] = ($pedidoAgendado->getPedido()!='' && $pedidoAgendado->getPedido()!=null) ? $pedidoAgendado->getPedido() : $pedidoAgendado->getNotaFiscal();
}
}
//$totalPedidosDisponiveisParaEntrega = $totalPedidosDia - $totalPedidosNaData - $totalPedidosQualquerHorario;
$totalPedidosDisponiveisParaEntrega = $totalPedidosDia - $totalPedidosNaData;
//$totalPedidosDisponiveisParaEntrega = $totalPedidosDia - ($totalPedidosManha+$totalPedidosTarde+$totalPedidosQualquerHorario);
$totalPedidosParaManha = $totalPedidosDisponiveisParaEntrega - $totalPedidosNaDataManha; // 12 pedidos
//$totalPedidosParaManha = $totalPedidosParaManha - $totalPedidosManha;
$totalPedidosParaTarde = $totalPedidosDisponiveisParaEntrega - $totalPedidosNaDataTarde; // 12 pedidos
//$totalPedidosParaTarde = $totalPedidosParaTarde - $totalPedidosTarde;
$periodos = [];
$pedidosManha = implode(',',$pedidosManha);
$pedidosTarde = implode(',',$pedidosTarde);
if($totalPedidosParaManha>0) {
$dataDesejada = $date->format('Y-m-d');
$dataHoje = $hoje->format('Y-m-d');
if($dataDesejada==$dataHoje) {
$hour = (int)$hoje->format('H');
if($hour<=11) {
//$periodos[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.$totalPedidosParaManha.') P:'.$pedidosManha];
$periodos[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.ceil($totalPedidosParaManha).')'];
}
} else {
//$periodos[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.$totalPedidosParaManha.') P:'.$pedidosManha];
$periodos[] = ['value'=>'De Manhã', 'text'=>'De Manhã('.ceil($totalPedidosParaManha).')'];
}
}
if($totalPedidosParaTarde>0) {
//$periodos[] = ['value'=>'À tarde', 'text'=>'À tarde('.$totalPedidosParaTarde.') P:'.$pedidosTarde];
$periodos[] = ['value'=>'À tarde', 'text'=>'À tarde('.ceil($totalPedidosParaTarde).')'];
}
if(($totalPedidosParaManha>0) && ($totalPedidosParaTarde>0)) {
$totalDisponivelNoDia = ceil($totalPedidosParaManha)+ceil($totalPedidosParaTarde);
$periodos[] = ['value'=>'Qualquer horário', 'text'=>'Qualquer horário('.$totalDisponivelNoDia.')'];
}
$periodos[] = ['value'=>'', 'text'=>''];
$pedidosNumeros = join(', ', $pedidosNumeros);
return new JsonResponse(['periodos'=>$periodosNovo, 'pedidos'=>$pedidosNumeros, 'totalPedidosNaData'=>$totalPedidosNaData, 'totalPedidosDia'=>$totalPedidosDia], 200);
}
public function getMenuContextoCard() {
return '<a style="position:absolute;right:10px;top:10px;" data-toggle="modal" data-target="#modal-problema-pedido" @click="alert();idCurrentPedido = pedidoTansito.id">
<i class="fa fa-bars" aria-hidden="true" style="color:orange; font-size:30px;"></i>
</a>';
}
/**
* @Route("/app-externo/ler-obs-pendente-de-leitura", name="pedidos_pendente_leitura_lida", methods={"POST"})
*/
public function pedidosPendentesLeituraLido(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if($pedido instanceof EntregaPedido){
$pedido->setIsObsLida(true);
$this->getDoctrine()->getManager()->flush();
}
return new JsonResponse(['pedidosLidos'=>$this->getPedidosNaoLidos()], 200);
}
/**
* @Route("/app-externo/busca-pedidos-com-obs-pendente-de-leitura", name="pedidos_pendente_leitura", methods={"GET"})
*/
public function pedidosPendentesLeitura(Request $request): Response
{
return new JsonResponse($this->getPedidosNaoLidos(), 200);
}
private function getPedidosNaoLidos() {
$pedidosResult = [];
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['isObsLida'=>false], array('id' => 'DESC'));
foreach ($pedidos as $pedido) {
$pedidosResult[] = ['id'=>$pedido->getId(), 'pedido'=>$pedido->getPedido(),'nf'=>$pedido->getNotaFiscal()];
}
return $pedidosResult;
}
/**
* @Route("/app-externo/busca-pedido-filter", name="busca_pedido_filter", methods={"POST"})
*/
public function buscaPedidoFilter(Request $request): Response
{
$data = json_decode($request->getContent(), false);
// // Tipo Filtro = $data->field
// // Valor: $data->value
// $pedidosResult = [];
// $pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilter($data->field, $data->value);
// $pedidosResult = $this->todosPedidosPorStatus();
// foreach ($pedidos as $pedido) {
// // Se quiser retornar na mesma posição dele na aba. capturar o status e concatenar na posição correta
// $pedidosResult['baixados'][] = $this->makeProdutoData($pedido);
// }
$pedidosResult = $this->todosPedidosPorStatus($data->value, $data->field, true, $data->tipo);
return new JsonResponse($pedidosResult, 200);
}
/**
* @Route("/app-externo/geraSenhas", name="geraSenhas")
*/
public function geraSenhas(UserPasswordEncoderInterface $passwordEncoder): Response
{
$usuarios = [
['nome'=>'kevin', 'id'=>478976],
['nome'=>'kawan', 'id'=>98702],
['nome'=>'adriel', 'id'=>465667]
];
foreach ($usuarios as $usuario) {
$nome = strtolower($usuario['nome']);
echo 'Login: ' . $nome . ' - Senha: ' . $usuario['id'] . '<br/>';
/** @var User $entity */
$entity = $this->getDoctrine()->getRepository(User::class)->find(16);
$nome = strtolower($usuario['nome']);
$password = $passwordEncoder->encodePassword($entity, $usuario['id']);
echo $password.'<br/>';
}
exit();
// $usuarios = $this->getDoctrine()->getRepository(User::class)->findAll();
// foreach ($usuarios as $usuario) {
// if($usuario->getEmail()!='bruno@moveispollo.com.br' && $usuario->getEmail()!='neto'){
// $caracteresPermitidos = '0123456789';
// // Gere a senha aleatória
// $senha = '';
// $tamanhoCaracteres = strlen($caracteresPermitidos);
// for ($i = 0; $i < 8; $i++) {
// $senha .= $caracteresPermitidos[rand(0, $tamanhoCaracteres - 1)];
// }
// $password = $passwordEncoder->encodePassword($usuario, $senha);
// $usuario->setPassword($password);
// $this->getDoctrine()->getManager()->flush();
// echo '######################################################<br/>';
// echo $usuario->getNome() . '<br/>';
// echo 'Login: ' . strtolower($usuario->getEmail()) . '<br/>';
// echo 'Senha: ' . $senha . '<br/>';
// }
// }
// exit();
}
/**
* @Route("/app-externo/enviar-imagem-link-assistencia", name="envia_imagem_por_link_assistencia", methods={"POST"})
*/
public function enviarLinkAssistencia(Request $request, HttpClientInterface $client): Response
{
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false,
)
);
$data = json_decode($request->getContent(), false);
$idPedido = $data->pedido;
$imageName = time();
$filename = "$imageName.jpeg";
$uploadfile = '/www/wwwroot/gestor.moveispollo.com.br/public/img_assistencia/'.$filename;
$data = file_get_contents($data->link, false, stream_context_create($arrContextOptions));
file_put_contents($uploadfile, $data);
$fotos = [];
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if($pedido->getFotosAssistencia()!='' && $pedido->getFotosAssistencia() !=null){
$fotos = json_decode($pedido->getFotosAssistencia());
}
$fotos[] = $filename;
$pedido->setFotosAssistencia(json_encode($fotos));
$this->getDoctrine()->getManager()->flush();
$fotos = json_decode($pedido->getFotos());
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$pedido->getNotas(), 'sinistros'=>$fotosSinistro, 'comprovante'=>$pedido->getComprovantePagamento(), 'fotos_assistencia'=>$fotosAssistencia],$this->todosPedidosPorStatus()), 200);
}
/**
* @Route("/app-externo/pedido-detalhe", name="pedido_detalhe", methods={"GET"})
*/
public function getDetalhePedido(Request $request, HttpClientInterface $client): Response
{
return $this->render('app_externo/telas/pedido.html.twig');
}
/**
* @Route("/app-externo/aceitacao-separador", name="aeitacao_separador", methods={"POST"})
*/
public function aceitacaoSeparador(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
$user = $this->getUser();
$idPedido = 0;
if(isset($data->pedido->id)){
$idPedido = $data->pedido->id;
} else {
$idPedido = $data->pedido;
}
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if(!$pedido instanceof EntregaPedido) {
return new JsonResponse([], 400);
}
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
if(!$pedido->getTempoGastoSeparacao()) {
// $messageBody = "O Pedido / NF *$numeroPedido* foi Aceito para *Montagem/Separação* pelo {$user->getNome()}.\n\nCliente: " . $pedido->getContato();
// $destinatarios = ['556291089053', '5562994542599'];
// foreach ($destinatarios as $destinatario) {
// // $destino = 'W';
// // if($destinatario=='556232337424') {
// // $destino = 'B';
// // }
// $this->sendMensagemViaWhatsapp("text", $destinatario, $messageBody, null, null, null, null);
// }
}
$pedido->setSeparadorAceitouAt(new \DateTime('now'));
if(isset($data->tempoGastoAceitacao)) {
$destinatariosPronto = ['556291089053', '556232337424'];
if($pedido->getColaboradorUser()){
$telefoneMotorista = $pedido->getColaboradorUser()->getTelefone();
$destinatariosPronto[] = $telefoneMotorista;
}
if($data->tempoGastoAceitacao=='Pronto') {
$messageBody = "A *Montagem/Separação* do Pedido / NF *$numeroPedido* está *Pronto*.\n\nCliente: " . $pedido->getContato();
foreach ($destinatariosPronto as $destinatario) {
$this->sendMensagemViaWhatsapp("text", $destinatario, $messageBody, null, null, null);
}
}
$pedido->setTempoGastoSeparacao($data->tempoGastoAceitacao);
if($data->tempoGastoAceitacao!='Até o Fim da Manhã' && $data->tempoGastoAceitacao!='Até o Fim da Tarde' && $data->tempoGastoAceitacao!='Pronto') {
if($data->tempoGastoAceitacao) {
$time = new \DateTime('now');
$time->add(new \DateInterval('PT' . $data->tempoGastoAceitacao . 'M'));
$pedido->setPrevisaoDataSeparacaoAt($time);
}
}
}
if($this->getIsAdmin()) {
$pedido->setSeparador($data->pessoa);
} else {
$pedido->setSeparador($user->getEmail());
}
//$pedido->setStatus('aceito');
$this->getDoctrine()->getManager()->flush();
// // Envio zap vendedor
// $usuarioVendedor = strtolower($pedido->getVendedor());
// $usarioVendedor = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioVendedor]);
// if($usarioVendedor instanceof User){
// $telefone = $usarioVendedor->getTelefone();
// $destino = 'W';
// if($telefone=='5562994542599') {
// $destino = 'B';
// }
// $this->sendMensagemViaWhatsapp("text", $telefone, $messageBody, null, null, null, $destino);
// }
// // Envio zap Cadastrante
// $usuarioCadastrante = strtolower($pedido->getCadastradoPor());
// $usuarioCadastrante = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioCadastrante]);
// if($usuarioCadastrante instanceof User){
// $telefone = $usuarioCadastrante->getTelefone();
// $destino = 'W';
// if($telefone=='5562994542599') {
// $destino = 'B';
// }
// $this->sendMensagemViaWhatsapp("text", $telefone, $messageBody, null, null, null, $destino);
// }
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/update-checkbox-pedido", name="update_checkbox_pedido", methods={"POST"})
*/
public function updateCheckBoxPedido(Request $request, HttpClientInterface $client): Response
{
$data = json_decode($request->getContent(), false);
if(!$this->getIsAdmin()){
return new JsonResponse(['message'=>'Não é admin'], 400);
}
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido->id);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse(['message'=>'Pedido não localizado'], 400);
}
// if($data->check == 'pedidoRealizadoCheck') {
// if(!$pedido->getSolicitarMontagemSaoJose() && !$pedido->getSolicitarSeparacaoSaoJose()) {
// return new JsonResponse(['message'=>'Necessário solicitar montagem/separação antecipadamente.'], 400);
// }
// }
// if($data->check == 'pedidoRealizadoCoimbraCheck'){
// if(!$pedido->getSolicitarMontagem() && !$pedido->getSolicitarSeparacao()) {
// return new JsonResponse(['message'=>'Necessário solicitar montagem/separação antecipadamente.'], 400);
// }
// }
$nameMethod = ucfirst($data->check);
$localidade = '';
if (strpos($nameMethod, 'SaoJose') !== false ||
$nameMethod=='PedidoMontandoRonald' ||
$nameMethod=='PedidoMontandoFabio' ||
$nameMethod=='PedidoMontandoRian' ||
$nameMethod=='AguardandoColeta' ||
$nameMethod=='IsColetado' ||
$nameMethod=='SolicitarMontagemSaoJose' ||
$nameMethod=='SolicitarSeparacao' ||
$nameMethod=='SolicitarSeparacaoSaoJose' ||
$nameMethod=='PedidoMontandoMontagemFinalizada') {
$nameMethodSet = 'set' . $nameMethod;
$nameMethodGet = 'get' . $nameMethod;
} else if($nameMethod=='PedidoImpressoGuilhermeCheck'){
$nameMethodSet = 'setPedidoImpressoGuilhermeCheck';
$nameMethodGet = 'getPedidoImpressoGuilhermeCheck';
} else if($nameMethod=='SolicitarMontagem') {
$nameMethodSet = 'set' . $nameMethod;
$nameMethodGet = 'get' . $nameMethod;
} else {
$nameMethodSet = 'set' . $nameMethod . 'At';
$nameMethodGet = 'get' . $nameMethod . 'At';
}
// if($nameMethod=='SolicitarMontagemSaoJose' || $nameMethod=='SolicitarSeparacaoSaoJose'){
// $pedido->setLocalidadeSaoJose('sj');
// }
// if($nameMethod=='SolicitarSeparacao' || $nameMethod=='SolicitarMontagem'){
// $pedido->setLocalidade('co');
// }
$valueUpdate = new \DateTime('now');
$getValue = $pedido->{$nameMethodGet}();
if($getValue instanceof \DateTime) {
$valueUpdate = null;
}
$pedido->{$nameMethodSet}($valueUpdate);
$enderecoEntrega = ($pedido->getNovoEnderecoEntrega() != '' && $pedido->getNovoEnderecoEntrega() != null) ? $pedido->getNovoEnderecoEntrega() : $pedido->getEndereco();
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
switch ($data->check) {
case 'pedidoRealizadoCheck':
$pedido->setLastUpdateStatus(new \DateTime('now'));
$pedido->setStatus('recebido');
break;
case 'pedidoRealizadoCoimbraCheck':
$pedido->setLastUpdateStatus(new \DateTime('now'));
$pedido->setStatus('recebido');
break;
case 'pedidoImpressoCheck':
// code...
break;
case 'pedidoEnderecoCheck':
//$dadosCliente = $this->getDadosCliente($pedido->getPedido(),$client);
//$messageBody = "*Endereço:* ".$dadosCliente['endereco'];
$messageBody = "*Endereço:* " . $enderecoEntrega;
$messageImagemBody = 'endereco-para-entrega.jpeg';
break;
case 'pedidoMontagemCheck':
$messageBody = "*Produtos*: Pré-montagem ou Separação.";
$messageImagemBody = 'montando-produtos.jpeg';
break;
case 'pedidoMotoristaCheck':
// code...
break;
case 'pedidoInstagramCheck':
$messageBody = "Ajude a Pollo Móveis seguindo o *Instagram*.\nCupom de desconto para seguidores.\n👉 instagram.com/pollomoveisescritorio\n👉 www.facebook.com/pollomoveisescritorio";
$messageImagemBody = 'instagram.jpeg';
break;
case 'pedidoGoogleCheck':
$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";
$messageImagemBody = 'entrega-concluida.jpeg';
break;
case 'pedidoImpressoCheckAtSaoJose':
// code...
break;
case 'pedidoPagoCheckAtSaoJose':
// code...
break;
case 'pedidoPagoCheck':
// code...
break;
case 'pedidoRetiradoCheckAtSaoJose':
// code...
break;
case 'pedidoCeletadoCheckAtSaoJose':
// code...
break;
case 'pedidoFotoProdutoCheckAtSaoJose':
// code...
break;
case 'pedidoFotoAssinaturaCheckAtSaoJose':
// code...
break;
case 'pedidoMontandoRonald':
// code...
break;
case 'pedidoMontandoFabio':
// code...
break;
case 'pedidoMontandoRian':
// code...
break;
case 'pedidoMontandoMontagemFinalizada':
// code...
break;
case 'aguardandoColeta':
// code...
break;
case 'isColetado':
// code...
break;
case 'pedidoImpressoGuilhermeCheck':
// code...
break;
case 'solicitarMontagem':
$this->createDemandaPedido($pedido, 'co', 'montagem', $data->pedido->solicitarMontagem);
break;
case 'solicitarMontagemSaoJose':
$this->createDemandaPedido($pedido, 'sj', 'montagem', $data->pedido->solicitarMontagemSaoJose);
break;
case 'solicitarSeparacao':
$this->createDemandaPedido($pedido, 'co', 'separacao', $data->pedido->solicitarSeparacao);
break;
case 'solicitarSeparacaoSaoJose':
$this->createDemandaPedido($pedido, 'sj', 'separacao', $data->pedido->solicitarSeparacaoSaoJose);
break;
default:
return new JsonResponse(['message'=>'Status não localizado'], 400);
break;
}
if($data->check=='pedidoMontagemCheck' || $data->check=='pedidoEnderecoCheck' || $data->check=='pedidoInstagramCheck' || $data->check=='pedidoGoogleCheck'){
$numeroTelefone = $pedido->getTelefone();
$telefones = explode('|', $numeroTelefone);
$messageImagemBody = 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/' . $messageImagemBody . '?v='.time();
$type = 'img';
if(count($telefones)>1){
if($telefones[0]!=$telefones[1]){
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
$this->sendMensagemViaWhatsapp($type, $telefones[1], $messageBody, $messageImagemBody, null, null);
} else {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
}
} else {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
}
}
if($data->check=='solicitarMontagem' || $data->check=='solicitarMontagemSaoJose'){
$type = "img";
$linkChecked = ($data->check=='solicitarMontagemSaoJose') ? 'geovair' : 'guilherme';
$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";
$img = 'https://polo.srvtmp.com.br/montagem.png?v=2';
if($data->check=='solicitarMontagem'){ // Coimbra
//$this->sendMensagemViaWhatsapp($type, "5562993126267", $messageBody, $img, null, null); // Guilherme
$this->sendMensagemViaWhatsapp($type, "5562993884202", $messageBody, $img, null, null); // Gregory
$this->sendMensagemViaWhatsapp($type, "5562994721501", $messageBody, $img, null, null); // Marcos
// $this->sendMensagemViaWhatsapp($type, "5562994542599", $messageBody, $img, null, null); // João Marcos
} else { // São José
$this->sendMensagemViaWhatsapp($type, "5562993602042", $messageBody, $img, null, null); // Geovair
$this->sendMensagemViaWhatsapp($type, "5562981352530", $messageBody, $img, null, null); // Mateus
$this->sendMensagemViaWhatsapp($type, "5562995698482", $messageBody, $img, null, null); // Samuel
//$this->sendMensagemViaWhatsapp($type, "5562981854439", $messageBody, $img, null, null); // RIAN
}
}
if($data->check=='solicitarSeparacao' || $data->check=='solicitarSeparacaoSaoJose'){
$type = "img";
$linkChecked = ($data->check=='solicitarSeparacaoSaoJose') ? 'geovair' : 'guilherme';
$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";
$img = 'https://polo.srvtmp.com.br/separacao.png?v=3';
if($data->check=='solicitarSeparacao'){ // Coimbra
//$this->sendMensagemViaWhatsapp($type, "5562993126267", $messageBody, $img, null, null); // Guilherme
$this->sendMensagemViaWhatsapp($type, "5562994542599", $messageBody, $img, null, null); // João Marcos
$this->sendMensagemViaWhatsapp($type, "5562992461439", $messageBody, $img, null, null); // Ronald
// $this->sendMensagemViaWhatsapp($type, "5562999720813", $messageBody, $img, null, null); // Fábio
// $this->sendMensagemViaWhatsapp($type, "5562994542599", $messageBody, $img, null, null); // João Marcos
} else { // São José
$this->sendMensagemViaWhatsapp($type, "5562993602042", $messageBody, $img, null, null); // Geovair
$this->sendMensagemViaWhatsapp($type, "5562981352530", $messageBody, $img, null, null); // Mateus
$this->sendMensagemViaWhatsapp($type, "5562995698482", $messageBody, $img, null, null); // Samuel
}
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
private function createDemandaPedido($pedido, $local, $tipo, $acao, $clienteVaiBuscarImediatamente=true, $isUrgente=true) {
$demanda = $this->getDoctrine()->getRepository(DemandaPedido::class)->findOneBy([
'pedido' => $pedido,
'local' => $local,
'tipo' => $tipo
]);
if(!$acao && $demanda instanceof DemandaPedido){
$this->getDoctrine()->getManager()->remove($demanda);
$this->getDoctrine()->getManager()->flush();
} else if(!$demanda instanceof DemandaPedido && $acao){
$demanda = new DemandaPedido();
$demanda->setPedido($pedido);
$demanda->setTipo($tipo);
$demanda->setLocal($local);
$demanda->setStatus('pendente');
$demanda->setCreatedAt(new \DateTime());
$demanda->setUpdatedAt(new \DateTime());
$demanda->setClienteVaiRetirarImediatamente($clienteVaiBuscarImediatamente);
$demanda->setIsUrgente($isUrgente);
$this->getDoctrine()->getManager()->persist($demanda);
$this->getDoctrine()->getManager()->flush();
}
}
/**
* @Route("/app-externo/checked/{checkname}/{pedido}", name="checked_pedido", methods={"GET"})
*/
public function checkedPedidoAction(Request $request, $checkname, $pedido): Response
{
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedido, 'deletedAt'=>null]);
$messageJs = 'Pedido não localizado!';
if($pedido instanceof EntregaPedido){
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
if($checkname=='guilherme'){
$pedido->setPedidoImpressoGuilhermeCheck(new \DateTime());
$this->getDoctrine()->getManager()->flush();
} else if($checkname=='geovair') {
$pedido->setPedidoPagoCheckAt(new \DateTime());
$this->getDoctrine()->getManager()->flush();
}
$messageJs = 'Você enviou uma informação na api e você imprimiu e deu andamento na montagem deste pedido.';
exit('<script>alert("'.$messageJs.'");document.location.href="/app-externo#'.$numeroPedido.'";</script>');
}
exit('<script>alert("'.$messageJs.'");document.location.href="/app-externo";</script>');
}
private function notificaClienteCriacaoCard($pedido) {
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
$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";
$messageImagemBody = 'pedido-recebido.jpeg';
$numeroTelefone = $pedido->getTelefone();
$telefones = explode('|', $numeroTelefone);
$messageImagemBody = 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/' . $messageImagemBody . '?v='.time();
$type = 'img';
$isRetirada = false;
if($pedido->getMeioEntrega()=='Retirar no Galpão Coimbra' || $pedido->getMeioEntrega()=='Retirar no Galpão São José' || $pedido->getMeioEntrega()=='Retirar Coimbra/São José'){
$isRetirada = true;
$linkLocalizacao = '';
$escritaAntes = 'Endereço para retirada dos produtos';
switch($pedido->getMeioEntrega()) {
case 'Retirar no Galpão Coimbra':
$linkLocalizacao = "*Depósito Coimbra:* Rua 209, 409 - St. Coimbra - Goiânia-Go\nhttps://goo.gl/maps/NFKaVRDiq1eai7jK8";
break;
case 'Retirar no Galpão São José':
$linkLocalizacao = "*Depósito São José:* Av. Dom Eduardo, 881 - St. São José, Goiânia-Go\nhttps://goo.gl/maps/3SLnM32FdSBjk25KA";
break;
case 'Retirar Coimbra/São José':
$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";
$escritaAntes = 'Endereço para retirada dos produtos em dois enderecos';
break;
default:
$linkLocalizacao = '';
$isRetirada = false;
break;
}
if($isRetirada){
$messageBody .= "\n\n*$escritaAntes:*\n\n$linkLocalizacao\n\nPix: 12.993.989/0001-60";
}
}
$messageBody_Rastreio = "Olá, acompanhe o status da sua entrega clicando no link abaixo\nhttps://app.moveispollo.com.br/acompanhamento/pedido/" . $pedido->getCodidoRastreio();
$messageImagemBody_Rastreio = 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/rastreio_pedido.png?v='.time();;
if(count($telefones)>1){
if($telefones[0]!=$telefones[1]){
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
$this->sendMensagemViaWhatsapp($type, $telefones[1], $messageBody, $messageImagemBody, null, null);
if(($pedido->getMeioEntrega()=='Pela Pollo Móveis' || $pedido->getMeioEntrega()=='Viagem pela Pollo Móveis')) {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody_Rastreio, $messageImagemBody_Rastreio, null, null);
$this->sendMensagemViaWhatsapp($type, $telefones[1], $messageBody_Rastreio, $messageImagemBody_Rastreio, null, null);
}
} else {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
if(($pedido->getMeioEntrega()=='Pela Pollo Móveis' || $pedido->getMeioEntrega()=='Viagem pela Pollo Móveis')) {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody_Rastreio, $messageImagemBody_Rastreio, null, null);
}
}
} else {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
if(($pedido->getMeioEntrega()=='Pela Pollo Móveis' || $pedido->getMeioEntrega()=='Viagem pela Pollo Móveis')) {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody_Rastreio, $messageImagemBody_Rastreio, null, null);
}
}
$userNotificatonVendedor = '';
// Envio zap vendedor
$usarioVendedor = $this->getDoctrine()->getRepository(ContatoBling::class)
->findOneBy(['nome'=>$pedido->getVendedor(), 'grupo'=>'Vendedor']);
if($usarioVendedor instanceof ContatoBling){
$telefoneItem = $usarioVendedor->getTelefone();
$contatosSplit = explode('|',$telefoneItem);
foreach ($contatosSplit as $contatoS){
$numeroTelefone = $this->filterCelular($contatoS);
$numeroTelefone = '55' . $numeroTelefone;
$this->sendMensagemViaWhatsapp("text", $numeroTelefone, $messageBody, null, null, null);
}
}
}
/**
* @Route("/app-externo/delete-image", name="delete_image_pedido", methods={"POST"})
*/
public function deleteImagePedido(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$user = $this->getUser();
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$this->getIsAdmin()) {
if($this->getIsEntregador() || $this->getIsEntregadorAux()){
return new JsonResponse($dados, 400);
}
if($pedido->getStatus()=='entregue' || $pedido->getStatus()=='baixado' || $pedido->getStatus()=='pendente_admin' ){
return new JsonResponse($dados, 400);
}
}
if($data->tipo=='nota') {
//$pedido->setNotas(null);
$fotosNota = json_decode($pedido->getNotas(), true);
$position = 0;
if(!isset($fotosNota[0])){
$pedido->setNotas(null);
} else {
foreach ($fotosNota as $key=>$fotoNota){
if($fotoNota==$data->foto){
unset($fotosNota[$key]);
}
$position++;
}
$pedido->setNotas(json_encode($fotosNota));
}
} else if($data->tipo=='comprovante') {
//$pedido->setComprovantePagamento(null);
$fotosComprovante = json_decode($pedido->getComprovantePagamento(), true);
$position = 0;
if(!isset($fotosComprovante[0])){
$pedido->setComprovantePagamento(null);
} else {
foreach ($fotosComprovante as $key=>$fotoComprovante){
if($fotoComprovante==$data->foto){
unset($fotosComprovante[$key]);
}
$position++;
}
$pedido->setComprovantePagamento(json_encode($fotosComprovante));
}
} else if($data->tipo=='pedido' || $data->tipo=='pedido_entregue') {
$fotosPedidos = json_decode($pedido->getFotos(), true);
$position = 0;
if(!isset($fotosPedidos[0])){
$pedido->setFotos(null);
} else {
foreach ($fotosPedidos as $key=>$fotoPedido){
if($fotoPedido==$data->foto){
unset($fotosPedidos[$key]);
}
$position++;
}
$pedido->setFotos(json_encode($fotosPedidos));
}
} else if($data->tipo=='sinistro') {
$fotosPedidos = json_decode($pedido->getFotosSinistro(), true);
$position = 0;
if(!isset($fotosPedidos[0])){
$pedido->setFotosSinistro(null);
} else {
foreach ($fotosPedidos as $key=>$fotoPedido){
if($fotoPedido==$data->foto){
unset($fotosPedidos[$key]);
}
$position++;
}
$pedido->setFotosSinistro(json_encode($fotosPedidos));
}
} else if($data->tipo=='assistencia') {
$fotosPedidos = json_decode($pedido->getFotosAssistencia(), true);
$position = 0;
if(!count($fotosPedidos)){
$pedido->getFotosAssistencia(null);
} else {
foreach ($fotosPedidos as $key=>$fotoPedido){
if($fotoPedido==$data->foto){
unset($fotosPedidos[$key]);
}
$position++;
}
$pedido->setFotosAssistencia(json_encode($fotosPedidos));
}
}
$this->getDoctrine()->getManager()->flush();
$fotos = json_decode($pedido->getFotos());
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$fotosNotas, 'sinistros'=>$fotosSinistro, 'comprovante'=>$fotosComprovantes, 'fotos_assistencia'=>$fotosAssistencia], $this->todosPedidosPorStatus()), 200);
}
/**
* @Route("/app-externo/busca-pedido", name="busca_pedido", methods={"GET"})
*/
public function buscaPedidoBling(Request $request, HttpClientInterface $client): Response
{
if($request->get('tipo')=='pedido' || $request->get('tipo')=='pedido_entregue') {
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$request->get('pedido'), 'deletedAt'=>null]);
if($pedido instanceof EntregaPedido){
return new JsonResponse(['message'=>"Este pedido já está cadastrado no sistema."], 400);
}
} else {
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$request->get('pedido'), 'deletedAt'=>null]);
if($pedido instanceof EntregaPedido){
return new JsonResponse(['message'=>"Este pedido já está cadastrado no sistema."], 400);
}
}
$dados = [];
if($request->get('tipo')=='pedido' || $request->get('tipo')=='pedido_entregue') {
$dados = $this->getPedido(trim($request->get('pedido')), $client, $request->get('tipo'));
} else {
$dados = $this->getNotaFiscal(trim($request->get('pedido')), $client, $request->get('tipo'));
}
return new JsonResponse($dados, 200);
}
/**
* @Route("/app-externo/busca-pedido-customizado-detalhe", name="busca_pedido_customizado_detalhe", methods={"GET"})
*/
public function buscaPedidoCustomizadoDetalheBling(Request $request, HttpClientInterface $client): Response
{
$pedidoLocal = $this->getDoctrine()->getRepository(EntregaPedido::class)
->findOneBy(['pedido'=>$request->get('p'), 'deletedAt'=>NULL]);
$pedidoReplace = str_replace('-Assistência','', $request->get('p'));
if(!$pedidoLocal instanceof EntregaPedido || $request->get('nf')=='s') {
$linkNf = $this->getNotaFiscalLink($pedidoReplace, $client);
if($linkNf!=''){
header("Location: " . $linkNf);
exit;
}
exit('Este link não corresponde à uma NF e nem pedido.');
}
$dados = $this->getPedido(trim($pedidoReplace), $client, true, $pedidoLocal);
$endereco = nl2br($pedidoLocal->getEnderecoSocialCustomizado());
$totalDeProdutos = 0;
$itens = json_decode($pedidoLocal->getItensPedidoCustomizado());
foreach ($itens as $item) {
$totalDeProdutos += $item->valorTotal;
}
$valor_com_desconto = $totalDeProdutos;
if($pedidoLocal->getDesconto() > 0){
//$valor_com_desconto = $totalDeProdutos - ($totalDeProdutos * ($pedidoLocal->getDesconto() / 100));
$valor_com_desconto = $totalDeProdutos - $pedidoLocal->getDesconto();
$valor_com_desconto = round($valor_com_desconto, 2);
}
//$valor_com_frete = $totalDeProdutos+$pedidoLocal->getFreteCustomizado();
$valor_com_desconto = $valor_com_desconto+$pedidoLocal->getFreteCustomizado();
return $this->render('app_externo/telas/pedido-customizado.html.twig', [
'dados'=> $dados, 'com_obs'=>true,
'razaoSocial'=> $pedidoLocal->getRazaoSocialCustomizado(),
'cliente'=> $pedidoLocal->getClienteCustomizado(),
'formaPagamento'=> $pedidoLocal->getFormaPagamentoCustomizado(),
'itens'=> $itens,
'frete'=> number_format($pedidoLocal->getFreteCustomizado(), 2, ',', '.'),
'endereco'=> $endereco,
'totalDeProdutos'=> number_format($valor_com_desconto, 2, ',', '.'),
'valorTotalComDesconto' => number_format($valor_com_desconto, 2, ',', '.'),
'vendedorCustomizado' => $pedidoLocal->getVendedorCustomizado(),
'desconto' => number_format($pedidoLocal->getDesconto(), 2, ',', '.')
]);
}
/**
* @Route("/app-externo/busca-pedido-detalhe", name="busca_pedido_detalhe", methods={"GET"})
*/
public function buscaPedidoDetalheBling(Request $request, HttpClientInterface $client): Response
{
$pedidoLocal = $this->getDoctrine()->getRepository(EntregaPedido::class)
->findOneBy(['pedido'=>$request->get('p'), 'deletedAt'=>NULL]);
$pedidoReplace = str_replace('-Assistência','', $request->get('p'));
if(!$pedidoLocal instanceof EntregaPedido || $request->get('nf')=='s') {
$linkNf = $this->getNotaFiscalLink($pedidoReplace, $client);
if($linkNf!=''){
header("Location: " . $linkNf);
exit;
}
exit('Este link não corresponde à uma NF e nem pedido.');
}
$dados = $this->getPedido(trim($pedidoReplace), $client, true, $pedidoLocal);
if($dados['endereco_entrega']==''){
$dados['endereco_entrega'] = $pedidoLocal->getNovoEnderecoEntrega();
}
$assinaturaAceitePedido = '';
$assinadoAt = '';
$demanda = $this->getDoctrine()->getRepository(DemandaPedido::class)->findOneBy(['pedido'=>$pedidoLocal]);
if($demanda instanceof DemandaPedido){
if($demanda->getAssinatura()!=null){
$assinaturaAceitePedido = $demanda->getAssinatura();
$assinadoAt = [
'dia' => $demanda->getAssinadoAt()->format('d'),
'mes' => $demanda->getAssinadoAt()->format('m'),
'ano' => $demanda->getAssinadoAt()->format('Y')
];
}
}
return $this->render('app_externo/telas/pedido.html.twig', ['dados'=>$dados, 'com_obs'=>true, 'assinatura'=>$assinaturaAceitePedido, 'assinadoAt'=>$assinadoAt]);
}
private function getNotaFiscalLink($numero, $client) {
$linkNf = '';
$response = $client->request(
'GET',
SincronizacaoController::URL_API_BLING . '/notafiscal/'.$numero.'/1/json/',
[
'query' => [
'apikey' => SincronizacaoController::KEY_API_POLLO
]
]
);
$statusCode = $response->getStatusCode();
if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
$content = $response->toArray();
if(isset($content['retorno'])){
if(isset($content['retorno']['notasfiscais'])){
if(count($content['retorno']['notasfiscais']) > 0) {
$notafiscal = $content['retorno']['notasfiscais'][0]['notafiscal'];
$linkNf = str_ireplace("\\","", $notafiscal['linkDanfe']);
}
}
}
}
return $linkNf;
}
/**
* @Route("/app-externo/get-pedidos-publico/{pedido}", name="get_pedidos_publico", methods={"GET"})
*/
public function getPedidosPublico(Request $request, $pedido): Response
{
$pedidosLocalizados = [];
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->getPedidoPorNotaOuPedido($pedido);
foreach ($pedidos as $pedido){
$pedidoNumero = empty($pedido->getPedido()) ? $pedido->getNotaFiscal() . '-NF' : $pedido->getPedido();
$pedidosLocalizados[] = [
'id' => $pedido->getId(),
'titulo' => $pedidoNumero
];
}
return new JsonResponse($pedidosLocalizados, 200);
}
/**
* @Route("/app-externo/get-images-pedido", name="get_images_pedido", methods={"GET"})
*/
public function getImagesPedido(Request $request): Response
{
$fotos = [];
$acessoPublico = false;
if(!$this->getUser() instanceof User){
$acessoPublico = true;
}
if($request->get('num_pedido')){
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$request->get('num_pedido'), 'deletedAt'=>null]);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse(['fotos'=>$fotos], 400);
}
} else {
$idPedido = $request->get('id');
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
}
if(!$pedido instanceof EntregaPedido){
return new JsonResponse(['fotos'=>$fotos], 200);
}
$fotos = json_decode($pedido->getFotos());
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
// Pega a demanda
$temAssinatura = false;
$demanda = $this->getDoctrine()->getRepository(DemandaPedido::class)->findOneBy(['pedido'=>$pedido]);
if($demanda instanceof DemandaPedido){
if($demanda->getAssinatura()!=null){
$fotosNotas[] = $demanda->getAssinatura();
$temAssinatura = true;
}
}
$motorista = '';
if($pedido->getColaboradorUser() instanceof User){
$motorista = strtoupper($pedido->getColaboradorUser()->getEmail());
}
$statusConcluido = '';
if($pedido->getStatus()=='entregue'){
$statusConcluido = 'Concluído';
}
$iniciouEntrega = false;
if($pedido->getStatus()=='transito'){
$iniciouEntrega = true;
}
if($acessoPublico) {
$localizacao = ($pedido->getLocalizacao()=='' || $pedido->getLocalizacao()==null) ? $pedido->getLinkEnderecoEntrega() : '';
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);
}
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);
}
private function abreviarNome($nomeCompleto) {
// Separa o nome completo em partes
$partes = explode(' ', $nomeCompleto);
// Se houver apenas um nome, retorna como está
if (count($partes) == 1) {
return $nomeCompleto;
}
// Mantém o primeiro e o último nome completos
$primeiroNome = array_shift($partes);
$ultimoNome = array_pop($partes);
// Converte os nomes intermediários para iniciais
$iniciais = '';
foreach ($partes as $parte) {
$iniciais .= strtoupper($parte[0]) . '. ';
}
// Concatena o primeiro nome, as iniciais e o último nome
return $primeiroNome . ' ' . $iniciais . $ultimoNome;
}
/**
* @Route("/app-externo/uplod-image-pedido-assistencia", name="upload_image_pedido_assistencia", methods={"POST"})
*/
public function uploadImagePedidoAssistencia(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$idPedido = $request->get('id');
//$ext = explode('.',$_FILES['file']['name']);
$imageName = rand(100000, 999999) . time();
$filename = "$imageName.jpeg";
$uploadfile = '/www/wwwroot/gestor.moveispollo.com.br/public/img_assistencia/'.$filename;
$img = str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($uploadfile, $data);
//if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$fotos = [];
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if($pedido->getFotosAssistencia()!='' && $pedido->getFotosAssistencia() !=null){
$fotos = json_decode($pedido->getFotosAssistencia());
}
$fotos[] = $filename;
$pedido->setFotosAssistencia(json_encode($fotos));
$this->getDoctrine()->getManager()->flush();
$fotos = json_decode($pedido->getFotos());
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$fotosNotas, 'sinistros'=>$fotosSinistro, 'comprovante'=>$fotosComprovantes, 'fotos_assistencia'=>$fotosAssistencia],$this->todosPedidosPorStatus()), 200);
//}
//return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante'=>'', 'assistencia'=>[]],$this->todosPedidosPorStatus()), 400);
}
/**
* @Route("/app-externo/uplod-image-pedido-sinitro", name="upload_image_pedido_sinistro", methods={"POST"})
*/
public function uploadImagePedidoSinistro(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$idPedido = $request->get('id');
//$ext = explode('.',$_FILES['file']['name']);
$imageName = rand(100000, 999999) . time();
$filename = "$imageName.jpeg";
$uploadfile = '/www/wwwroot/gestor.moveispollo.com.br/public/img_sinistro/'.$filename;
$img = str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($uploadfile, $data);
//if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$fotos = [];
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if($pedido->getFotosSinistro()!='' && $pedido->getFotosSinistro() !=null){
$fotos = json_decode($pedido->getFotosSinistro());
}
$fotos[] = $filename;
$pedido->setFotosSinistro(json_encode($fotos));
$this->getDoctrine()->getManager()->flush();
$fotos = json_decode($pedido->getFotos());
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$fotosNotas, 'sinistros'=>$fotosSinistro, 'comprovante'=>$fotosComprovantes, 'fotos_assistencia'=>$fotosAssistencia], $this->todosPedidosPorStatus()), 200);
//}
//return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante'=>'', 'assistencia'=>[]],$this->todosPedidosPorStatus()), 400);
}
/**
* @Route("/app-externo/uplod-image-comprovante", name="upload_image_comprovante", methods={"POST"})
*/
public function uploadImageComprovante(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$idPedido = $request->get('id');
//$ext = explode('.',$_FILES['file']['name']);
$imageName = rand(100000, 999999) . time();
$filename = "$imageName.jpeg";
$uploadfile = '/www/wwwroot/gestor.moveispollo.com.br/public/img_comprovante_pagamento/'.$filename;
$img = str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($uploadfile, $data);
//if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$fotos = [];
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if($pedido->getComprovantePagamento()!='' && $pedido->getComprovantePagamento() !=null){
$fotos = json_decode($pedido->getComprovantePagamento());
}
$fotos[] = $filename;
$pedido->setComprovantePagamento(json_encode($fotos));
$this->getDoctrine()->getManager()->flush();
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
$todosPedios = [];
if($this->getUser() instanceof User){
$todosPedios = $this->todosPedidosPorStatus();
}
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$fotosNotas, 'sinistros'=>$fotosSinistro, 'comprovante'=>$fotosComprovantes, 'fotos_assistencia'=>$fotosAssistencia], $todosPedios), 200);
#### ANTIGA
// $pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
// $pedido->setComprovantePagamento($filename);
// $this->getDoctrine()->getManager()->flush();
// $fotos = json_decode($pedido->getFotos());
// $fotosSinistro = json_decode($pedido->getFotosSinistro());
// $fotosAssistencia = json_decode($pedido->getFotosAssistencia());
// return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$pedido->getNotas(), 'sinistros'=>$fotosSinistro, 'comprovante'=>$pedido->getComprovantePagamento(), 'fotos_assistencia'=>$fotosAssistencia], $this->todosPedidosPorStatus()), 200);
#### ANTIGA
//}
//return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante' =>'', 'assistencia'=>[]], $this->todosPedidosPorStatus()), 400);
}
/**
* @Route("/app-externo/uplod-image-pedido", name="upload_image_pedido", methods={"POST"})
*/
public function uploadImagePedido(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$idPedido = $request->get('id');
//$ext = explode('.',$_FILES['file']['name']);
$imageName = rand(100000, 999999) . time();
$filename = "$imageName.jpeg";
$uploadfile = '/www/wwwroot/gestor.moveispollo.com.br/public/img_pedidos/'.$filename;
$img = str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($uploadfile, $data);
//if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$fotos = [];
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if($pedido->getFotos()!='' && $pedido->getFotos() !=null){
$fotos = json_decode($pedido->getFotos());
}
$fotos[] = $filename;
$pedido->setFotos(json_encode($fotos));
$this->getDoctrine()->getManager()->flush();
$fotos = json_decode($pedido->getFotos());
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
$todosPedios = [];
if($this->getUser() instanceof User){
$todosPedios = $this->todosPedidosPorStatus();
}
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$fotosNotas, 'sinistros'=>$fotosSinistro, 'comprovante'=>$fotosComprovantes, 'fotos_assistencia'=>$fotosAssistencia], $todosPedios), 200);
//}
//return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante' =>'', 'assistencia'=>[]], $this->todosPedidosPorStatus()), 400);
}
/**
* @Route("/app-externo/uplod-image-nota", name="upload_image_nota", methods={"POST"})
*/
public function uploadImageNota(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$idPedido = $request->get('id');
//$ext = explode('.',$_FILES['file']['name']);
$imageName = rand(100000, 999999) . time();
$filename = "$imageName.jpeg";
$uploadfile = '/www/wwwroot/gestor.moveispollo.com.br/public/img_notas/'.$filename;
$img = str_replace(['data:image/jpg;base64,','data:image/jpeg;base64,'], ['',''], $data->dataFile);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
file_put_contents($uploadfile, $data);
//if (move_uploaded_file($_FILES['file']['tmp_name'], $uploadfile)) {
$fotos = [];
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
if($pedido->getNotas()!='' && $pedido->getNotas() !=null){
$fotos = json_decode($pedido->getNotas());
}
$fotos[] = $filename;
$pedido->setNotas(json_encode($fotos));
$this->getDoctrine()->getManager()->flush();
$fotosSinistro = json_decode($pedido->getFotosSinistro());
$fotosAssistencia = json_decode($pedido->getFotosAssistencia());
$fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$fotosNotas = json_decode($pedido->getNotas());
// $pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($idPedido);
// $pedido->setNotas($filename);
// $this->getDoctrine()->getManager()->flush();
// $fotos = json_decode($pedido->getFotos());
// $fotosSinistro = json_decode($pedido->getFotosSinistro());
// $fotosAssistencia = json_decode($pedido->getFotosAssistencia());
// $fotosComprovantes = json_decode($pedido->getComprovantePagamento());
$todosPedios = [];
if($this->getUser() instanceof User){
$todosPedios = $this->todosPedidosPorStatus();
}
return new JsonResponse(array_merge(['fotos'=>$fotos, 'notas'=>$fotosNotas, 'sinistros'=>$fotosSinistro, 'comprovante'=>$fotosComprovantes, 'fotos_assistencia'=>$fotosAssistencia], $todosPedios), 200);
//}
//return new JsonResponse(array_merge(['fotos'=>[], 'notas'=>'', 'sinistros'=>[], 'comprovante' =>'', 'assistencia'=>[]], $this->todosPedidosPorStatus()), 400);
}
/**
* @Route("/app-externo/muda_status_novos_pedidos", name="muda_status_novos_pedidos", methods={"POST"})
*/
public function muda_status_novos_pedidos(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
if($data->tipo=='pago'){
$pedido->setIsPagoGeralAt(new \DateTime());
} else {
$pedido->setIsEntregueGeralAt(new \DateTime());
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/edita-entrega", name="edita_entrega", methods={"POST"})
*/
public function editaEntrega(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedidoLocalizado = false;
$esperarClientePagar = 'Não';
if(isset($data->esperarClientePagar)){
$esperarClientePagar = $data->esperarClientePagar;
}
$entregaNova = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->id);
// if($data->nota!='') {
// $pedidoId = intval($data->nota);
// $entregaNova = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$pedidoId, 'deletedAt'=>null]);
// } else {
// $pedidoId = intval($data->pedido);
// $entregaNova = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoId, 'deletedAt'=>null]);
// }
if(!$entregaNova instanceof EntregaPedido) {
return new JsonResponse(['message'=>'Este pedido não existe no sistema.'], 400);
}
// validações somente para cadastro de vendedor
if($this->getIsVendedor()) {
if(
($data->assistencia=='Sim' && $data->periodosEntrega=='' && $data->meioEntrega=='') /* Validações assistencia */
||
($data->assistencia=='Não' && $data->periodosEntrega=='' && $data->meioEntrega=='' &&
$data->formaPagamento=='' && $data->periodosEntrega=='') /* Validações não assistencia */
) {
return new JsonResponse(['message'=>'Todos os campos do formulário são obrigatórios para o cadastro do pedido.'], 400);
}
}
$user = $this->getUser();
$entregaNova->setUpdatedAt(new \DateTime('now'));
$urgente = false;
if(isset($data->isUrgente)) {
$urgente = ($data->isUrgente=='Sim') ? true : false;
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->montagem)) {
$entregaNova->setMontagem($data->montagem);
}
}
if(isset($data->separarMontarPedido)) {
$entregaNova->setSepararMontarPedido($data->separarMontarPedido);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->assistencia)) {
$entregaNova->setAssistencia($data->assistencia);
}
}
// if(isset($data->tipoDocumento)) {
// $entregaNova->setTipoDocumento($data->tipoDocumento);
// }
if(isset($data->formaPagamento)) {
$entregaNova->setFormaPagamento($data->formaPagamento);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->periodosEntrega)) {
$entregaNova->setPeriodoEntrega($data->periodosEntrega);
if(isset($data->horarioEntrega)) {
if($data->horarioEntrega!="Não informado"){
$horario = \DateTime::createFromFormat('H:i', $data->horarioEntrega);
$entregaNova->setHorarioEntrega($horario);
}
}
}
}
if(isset($data->meioEntrega)) {
$entregaNova->setMeioEntrega($data->meioEntrega);
}
if(isset($data->montarMoveis)) {
$entregaNova->setMontarMoveis($data->montarMoveis);
}
$entregaNova->setIsUrgente($urgente);
if(isset($data->observacaoCadastro)){
$entregaNova->setObservacaoCadastro($data->observacaoCadastro);
}
if(isset($data->endereco)){
$entregaNova->setEndereco($data->endereco);
if($data->endereco!=''){
$enderecoEntregaParaGeocode = $data->endereco;
}
}
if(isset($data->logradouro)){
if($data->logradouro!=''){
$endereco = $data->logradouro;
if(isset($data->enderecoComplemento)){
if($data->enderecoComplemento!=''){
$endereco .= ', ' . $data->enderecoComplemento . ', CEP: ' . $data->cepBusca;
}
}
$entregaNova->setNovoEnderecoEntrega($endereco);
$enderecoEntregaParaGeocode = $endereco;
}
// $entregaNova->setNovoEnderecoEntrega($data->novoEnderecoEntrega);
// if($data->novoEnderecoEntrega!=''){
// $enderecoEntregaParaGeocode = $data->novoEnderecoEntrega;
// }
}
if(isset($data->enderecoPadraoGoogle)){
if($data->enderecoPadraoGoogle!=''){
$entregaNova->setNovoEnderecoEntrega($data->enderecoPadraoGoogle);
$enderecoEntregaParaGeocode = $data->enderecoPadraoGoogle;
}
}
if(isset($data->pontoReferencia)){
if($data->pontoReferencia!=''){
$entregaNova->setEnderecoPontoReferencia($data->pontoReferencia);
}
}
$entregaNova->setContato($data->contato);
if(isset($data->tipoFrete)){
$entregaNova->setTipoFrete($data->tipoFrete);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->embalagem)){
$entregaNova->setEmbalagem($data->embalagem);
}
}
if(!$pedidoLocalizado){
$this->getDoctrine()->getManager()->persist($entregaNova);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->estaPago)){
$entregaNova->setEstaPago($data->estaPago);
} else {
$entregaNova->setEstaPago("Não");
}
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->receberNaEntrega)){
$entregaNova->setReceberNaEntrega($data->receberNaEntrega);
} else {
$entregaNova->setReceberNaEntrega("Não");
}
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->despacharTrocar)){
$entregaNova->setDespacharTrocar($data->despacharTrocar);
}
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->ladoMontagemBalcao) && $data->ladoMontagemBalcao!=''){
$entregaNova->setLadoMontagemBalcao($data->ladoMontagemBalcao);
}
}
if(isset($data->tipoDocumento)) {
$entregaNova->setTipoDocumento($data->tipoDocumento);
}
if(isset($data->estaPagoLoja)) {
$entregaNova->setPagoNaLoja($data->estaPagoLoja);
}
if(isset($data->cnpj)) {
$entregaNova->setCnpj($data->cnpj);
}
if(isset($data->linkEnderecoEntrega)){
$entregaNova->setLinkEnderecoEntrega($data->linkEnderecoEntrega);
}
if($this->getIsVendedor() || $this->getIsAdmin()) {
if(isset($data->entregarHoje)) {
$entregaNova->setEntregarHoje($data->entregarHoje);
if($data->entregarHoje=='Agendar') {
if(isset($data->dataEntrega)) {
$dataEntrega = \DateTime::createFromFormat('Y-m-d', $data->dataEntrega);
$dataEntrega->setTime(23, 59, 59);
if($dataEntrega instanceof \DateTime) {
$entregaNova->setDataEntrega($dataEntrega);
}
}
}
}
}
if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis') && $esperarClientePagar=='Não') {
if(isset($data->dataEntrega)) {
$dataEntrega = \DateTime::createFromFormat('d/m/Y', $data->dataEntrega);
$dataEntrega->setTime(23, 59, 59);
if($dataEntrega instanceof \DateTime) {
$entregaNova->setDataEntrega($dataEntrega);
}
}
}
if(isset($data->linkShare)) {
$entregaNova->setLinkShare($data->linkShare);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->desejaEnviarZapSeparador)){
if(isset($data->meioEntrega) && isset($data->desejaEnviarZapSeparador)){
$entregaNova->setDesejaEnviarZapSeparador($data->desejaEnviarZapSeparador);
}
}
}
if(isset($data->solicitarColeta)) {
$entregaNova->setSolicitarColeta($data->solicitarColeta);
}
if(isset($data->cotarFrete)){
$entregaNova->setCotarFrete($data->cotarFrete);
}
if(isset($data->observacaoCadastro)){
$observacao = $data->observacaoCadastro;
}
if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis')) {
if(isset($data->regeocodifica)){
if($data->regeocodifica){
if($enderecoEntregaParaGeocode!=''){
$coordenadasDoEndereco = $this->decodificaEndereco($enderecoEntregaParaGeocode);
if($coordenadasDoEndereco!==false){
if(isset($coordenadasDoEndereco['latitude']) && isset($coordenadasDoEndereco['longitude'])){
$entregaNova->setLatitude($coordenadasDoEndereco['latitude']);
$entregaNova->setLongitude($coordenadasDoEndereco['longitude']);
$linkEndereco = "https://waze.com/ul?ll=".$coordenadasDoEndereco['latitude'].",".$coordenadasDoEndereco['longitude']."&navigate=yes";
$entregaNova->setLinkEnderecoEntrega($linkEndereco);
$entregaNova->setEnderecoEntrega($enderecoEntregaParaGeocode);
}
} else {
return new JsonResponse(['Erro em geolocalizar'], 400);
}
}
}
}
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/cadastra-entrega", name="cadastra_entrega", methods={"POST"})
*/
public function cadastraEntrega(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedidoLocalizado = false;
$enderecoEntregaParaGeocode = '';
$esperarClientePagar = 'Não';
if(isset($data->esperarClientePagar)) {
$esperarClientePagar = $data->esperarClientePagar;
}
if(isset($data->meioEntrega)){
if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis') && $esperarClientePagar=='Não') {
if(!isset($data->dataEntrega)) {
return new JsonResponse(['message'=>'Informe a data de entrega!'], 400);
}
if($data->dataEntrega=='') {
return new JsonResponse(['message'=>'Informe a data de entrega!'], 400);
}
if($data->periodosEntrega=='lotado'){
return new JsonResponse(['message'=>'O período selecionado está lotado. Tente outro período.'], 400);
}
// // Validar a disponibilidade por periodo na data de entrega
// $date = \DateTime::createFromFormat('d/m/Y', $data->dataEntrega);
// $totalPedidosDia = $this->getTotalPedidosDia($date);
// $totalPorPeriodo = ($data->periodosEntrega=='Qualquer Horário') ? $totalPedidosDia : ($totalPedidosDia/2);
// $totalPedidosNaData = $this->getDoctrine()->getRepository(EntregaPedido::class)
// ->getPedidosAgendadosNaData($date->format('Y-m-d'), $date->format('Y-m-d'), $data->periodosEntrega);
// $totalPedidosNaData = count($totalPedidosNaData); // 49337
// exit("totalPorPeriodo $totalPorPeriodo - totalPedidosNaData: $totalPedidosNaData");
// if($totalPedidosNaData >= $totalPedidosDia) {
// return new JsonResponse(['message'=>'Não há vaga para entregar esse pedido nessa data e nesse período!'], 400);
// }
}
}
if(isset($data->tipo)) {
if($data->tipo=='nf') {
$pedidoId = intval($data->numeroNf);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$pedidoId, 'deletedAt'=>null]);
} else {
$pedidoId = intval($data->numeroPedido);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoId, 'deletedAt'=>null]);
// if(!$pedido instanceof EntregaPedido) {
// $pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedidoId.'-Assistência']);
// }
}
}
if($pedido instanceof EntregaPedido) {
return new JsonResponse(['message'=>'Este pedido já existe no sistema #1.'], 400);
// if(!$this->isAdmin() && !$this->getIsVendedor()) {
// return new JsonResponse(['message'=>'Este pedido já existe no sistema.'], 400);
// }
$pedidoLocalizado = true;
$entregaNova = $pedido;
} else {
$entregaNova = new EntregaPedido();
}
// validações somente para cadastro de vendedor
// if($this->getIsVendedor()) {
// if(
// ($data->assistencia=='Sim' && $data->periodosEntrega=='' && $data->meioEntrega=='') /* Validações assistencia */
// ||
// ($data->assistencia=='Não' && $data->periodosEntrega=='' && $data->meioEntrega=='' &&
// $data->formaPagamento=='' && $data->periodosEntrega=='') /* Validações não assistencia */
// ) {
// return new JsonResponse(['message'=>'Todos os campos do formulário são obrigatórios para o cadastro do pedido.'], 400);
// }
// }
// if(isset($cliente['endereco'])) {
// if($cliente['endereco']!='') {
// $entregaNova->setEndereco($cliente['endereco']);
// $enderecoEntregaParaGeocode = $cliente['endereco'];
// }
// }
if(isset($data->endereco) && $data->endereco!=''){
$entregaNova->setEndereco($data->endereco);
$enderecoEntregaParaGeocode = $data->endereco;
}
if(isset($data->endereco_entrega) && $data->endereco_entrega!=''){
$entregaNova->setEndereco($data->endereco_entrega);
$enderecoEntregaParaGeocode = $data->endereco_entrega;
}
$numeroNf = '';
$numeroPedido = '';
if($data->numeroPedido=='') {
$numeroPedido = $data->numeroNf;
$numeroNf = $data->numeroNf;
}
if($data->numeroNf=='') {
$numeroNf = '';
$numeroPedido = $data->numeroPedido;
} else {
$numeroNf = $data->numeroNf;
$numeroPedido = $data->numeroPedido;
}
//$numeroTelefone = preg_replace('/[^0-9]/', '', $data->telefone);
//$numeroTelefone ='55' . $numeroTelefone;
$user = $this->getUser();
$entregaNova->setIsEntregue(false);
$entregaNova->setStatus('pendente');
$entregaNova->setCreatedAt(new \DateTime('now'));
$entregaNova->setPedido($numeroPedido);
$entregaNova->setTelefone($data->telefone);
$entregaNova->setTipoBuscaCadastro($data->tipo);
$entregaNova->setNotaFiscal($numeroNf);
//$entregaNova->setEndereco($data->endereco);
$entregaNova->setVendedor($data->vendedor);
$entregaNova->setCadastradoPor($user->getNome());
$entregaNova->setUpdatedAt(new \DateTime('now'));
if(isset($data->itens)){
if($data->itens!=''){
$entregaNova->setItensPedido(json_encode($data->itens));
}
}
// Atualiza ultima movimentação de status
$entregaNova->setLastUpdateStatus(new \DateTime('now'));
$urgente = false;
if(isset($data->isUrgente)) {
$urgente = ($data->isUrgente=='Sim') ? true : false;
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->montagem)) {
$entregaNova->setMontagem($data->montagem);
}
}
if(isset($data->separarMontarPedido)) {
$entregaNova->setSepararMontarPedido($data->separarMontarPedido);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->assistencia)) {
$entregaNova->setAssistencia($data->assistencia);
}
}
if(isset($data->tipoDocumento)) {
$entregaNova->setTipoDocumento($data->tipoDocumento);
}
if(isset($data->origemMontagem)) {
$entregaNova->setOrigemMontagem($data->origemMontagem);
}
if(isset($data->formaPagamento)) {
$entregaNova->setFormaPagamento($data->formaPagamento);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->periodosEntrega)) {
$entregaNova->setPeriodoEntrega($data->periodosEntrega);
if(isset($data->horarioEntrega)) {
$horario = \DateTime::createFromFormat('H:i', $data->horarioEntrega);
$entregaNova->setHorarioEntrega($horario);
}
}
}
if(isset($data->meioEntrega)) {
$entregaNova->setMeioEntrega($data->meioEntrega);
}
if(isset($data->montarMoveis)) {
$entregaNova->setMontarMoveis($data->montarMoveis);
}
$entregaNova->setIsUrgente($urgente);
if(isset($data->observacaoCadastro)){
$entregaNova->setObservacaoCadastro($data->observacaoCadastro);
}
if(isset($data->logradouro)){
if($data->logradouro!=''){
$endereco = $data->logradouro;
if(isset($data->enderecoComplemento)){
if($data->enderecoComplemento!=''){
$endereco .= ', ' . $data->enderecoComplemento . ', CEP: ' . $data->cepBusca;
}
}
$entregaNova->setNovoEnderecoEntrega($endereco);
$entregaNova->setEnderecoEntrega($endereco);
$enderecoEntregaParaGeocode = $endereco;
}
}
if(isset($data->enderecoPadraoGoogle)){
if($data->enderecoPadraoGoogle!=''){
$entregaNova->setNovoEnderecoEntrega($data->enderecoPadraoGoogle);
$entregaNova->setEnderecoEntrega($data->enderecoPadraoGoogle);
$enderecoEntregaParaGeocode = $data->enderecoPadraoGoogle;
}
}
if(isset($data->pontoReferencia)){
if($data->pontoReferencia!=''){
$entregaNova->setEnderecoPontoReferencia($data->pontoReferencia);
}
}
$entregaNova->setContato($data->contato);
if(isset($data->tipoFrete)){
$entregaNova->setTipoFrete($data->tipoFrete);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->embalagem)){
$entregaNova->setEmbalagem($data->embalagem);
}
}
if(!$pedidoLocalizado){
$this->getDoctrine()->getManager()->persist($entregaNova);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->estaPago)){
$entregaNova->setEstaPago($data->estaPago);
} else {
$entregaNova->setEstaPago("Não");
}
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->receberNaEntrega)){
$entregaNova->setReceberNaEntrega($data->receberNaEntrega);
} else {
$entregaNova->setReceberNaEntrega("Não");
}
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->despacharTrocar)){
$entregaNova->setDespacharTrocar($data->despacharTrocar);
}
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->ladoMontagemBalcao) && $data->ladoMontagemBalcao!=''){
$entregaNova->setLadoMontagemBalcao($data->ladoMontagemBalcao);
}
}
if(isset($data->estaPagoLoja)){
$entregaNova->setPagoNaLoja($data->estaPagoLoja);
}
if(isset($data->cnpj)){
$entregaNova->setCnpj($data->cnpj);
}
if(isset($data->linkEnderecoEntrega)){
$entregaNova->setLinkEnderecoEntrega($data->linkEnderecoEntrega);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->entregarHoje)) {
$entregaNova->setEntregarHoje($data->entregarHoje);
if($data->entregarHoje=='Agendar') {
if(isset($data->dataEntrega)) {
$dataEntrega = \DateTime::createFromFormat('Y-m-d', $data->dataEntrega);
$dataEntrega->setTime(23, 59, 59);
if($dataEntrega instanceof \DateTime) {
$entregaNova->setDataEntrega($dataEntrega);
}
}
}
}
}
if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis') && $esperarClientePagar=='Não') {
if(isset($data->dataEntrega)) {
$dataEntrega = \DateTime::createFromFormat('d/m/Y', $data->dataEntrega);
$dataEntrega->setTime(23, 59, 59);
if($dataEntrega instanceof \DateTime) {
$entregaNova->setDataEntrega($dataEntrega);
}
}
}
if(isset($data->linkShare)) {
$entregaNova->setLinkShare($data->linkShare);
}
if($this->getIsVendedor() || $this->getIsAdmin()){
if(isset($data->desejaEnviarZapSeparador)){
if(isset($data->meioEntrega) && isset($data->desejaEnviarZapSeparador)){
$entregaNova->setDesejaEnviarZapSeparador($data->desejaEnviarZapSeparador);
if($data->desejaEnviarZapSeparador=='Sim'){
$type='text';
$montarOuNao = "";
// estaPago => Mostrar label
// receberNaEntrega => Mostrar label
// pagoNaLoja => Mostrar label
// desejaEnviarZapSeparador => Veriicar para mandar com link do pedido para os separadorres Link do bling
// Chegou um novo *pedido Nº xxx* para separação.
// Não montar. Usar Embalagem
// Favor Montar os itens
// São jose
// Geovair => 5562993602042
// Mateus => 5562981352530
// Marcos => 5562994721501
// Coimbra
// Ronald => 5562993771776
// Fabio => 5562999720813
// João Marcos => 5562994542599
$destinatariosSaoJose = ['5562993602042'];
$destinatariosCoimbra = [];
$destinatariosTodos = array_merge($destinatariosSaoJose,$destinatariosCoimbra);
if($data->meioEntrega=='Retirar no Galpão Coimbra') {
$destinatarios = $destinatariosCoimbra; // Coimbra
} else if($data->meioEntrega=='Retirar no Galpão São José') {
$destinatarios = $destinatariosSaoJose; // São José
} else {
$destinatarios = $destinatariosTodos;
}
if($data->contato){
$montarOuNao .= "*Nome:* {$data->contato}\n\n";
}
if($entregaNova->getIsUrgente()){
$montarOuNao .= "*URGENTE!*\n\n";
}
if(isset($data->tipoDocumento)){
$montarOuNao .= "*Emitir*: " . $data->tipoDocumento."\n\n";
}
if(isset($data->montarMoveis)) {
if($data->montarMoveis=='Não') {
if(isset($data->embalagem)) {
$montarOuNao .= "*Montar Móveis*: Não \n\n*Usar a embalagem:* " . $data->embalagem . "\n\n";
} else {
$montarOuNao .= "*Montar Pedido*: Não\n\n";
$montarOuNao .= "*Montagem*: ".$data->montarMoveis."\n\n";
}
} else {
$montarOuNao .= "*Montar Móveis*: Sim\n\n";
if(isset($data->ladoMontagemBalcao) && $data->ladoMontagemBalcao != ''){
$montarOuNao .= "*Lado Balcão*: {$data->ladoMontagemBalcao}\n\n";
}
$montarOuNao .= "*Montagem*: ".$data->montarMoveis."\n\n";
}
} else {
$montarOuNao .= "*Montar Móveis*: Não\n\n";
if(isset($data->montarMoveis)){
$montarOuNao .= "*Montagem*: ".$data->montarMoveis."\n\n";
}
}
// if($entregaNova->getSepararMontarPedido()){
// $montarOuNao .= "*Separar ou Montar Pedido*: ".$entregaNova->getSepararMontarPedido()."\n";
// } else {
// $montarOuNao .= "*Separar ou Montar Pedido*: Não \n";
// }
if($entregaNova->getEntregarHoje()=='Agendar') {
$montarOuNao .= "*Data da Entrega*: " . $entregaNova->getDataEntrega()->format('d/m/Y') . "\n\n";
} else {
if(isset($data->montarMoveis)){
if($data->montarMoveis!='Sim' && $data->montarMoveis!='Não'){
$montarOuNao .= "*Entregar Hoje*: ".$entregaNova->getEntregarHoje()." \n\n";
}
}
}
if($entregaNova->getPeriodoEntrega()!="Agendar Horário") {
$montarOuNao .= "*Período da Entrega*: " . $entregaNova->getPeriodoEntrega() . "\n\n";
}
if($entregaNova->getEntregarHoje()=='Agendar') {
if($entregaNova->getPeriodoEntrega()=="Agendar Horário") {
$montarOuNao .= "*Horário da Entrega*: " . $entregaNova->getHorarioEntrega()->format('H:i') . "\n\n";
}
}
$montarOuNao .= "*Observações*: " . $entregaNova->getObservacaoCadastro();
if($numeroPedido=='') {
$numeroPedido = $numeroNf;
$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";
} else {
$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";
}
//if($data->numeroNf=='') {
$messageBody = $messageBody . "\n\n" . 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' . $numeroPedido;
//}
//$destinatarios = ['556291089053', '5562983281823']; // TESTE
foreach ($destinatarios as $destinatario) {
$this->sendMensagemViaWhatsapp($type, $destinatario, $messageBody, null, null, null);
}
}
}
}
}
if(isset($data->cotarFrete)){
$entregaNova->setCotarFrete($data->cotarFrete);
if($data->cotarFrete=='Sim'){
$messageBody = "Favor cotar o valor do frete do *pedido Nº: $numeroPedido*\n\n" . "Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
$this->sendMensagemViaWhatsapp('text', '5562993126267', $messageBody, null, null, null); // Guilherme
//$this->sendMensagemViaWhatsapp('text', '556291089053', $messageBody, null, null, null); // TESTE
}
}
if(isset($data->solicitarColeta)) {
$entregaNova->setSolicitarColeta($data->solicitarColeta);
if($data->solicitarColeta=='Sim'){
if(isset($data->nomeTrasportadora)) {
if($data->nomeTrasportadora==''){
return new JsonResponse(['mensagem'=>'Nesse caso o nome da transportadora é obrigatório.'], 400);
} else {
$entregaNova->setNomeTransportadora($data->nomeTrasportadora);
$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";
$this->sendMensagemViaWhatsapp('text', '5562993126267', $messageBody, null, null, null); // Guilherme
}
} else {
return new JsonResponse([], 400);
}
}
}
if(isset($data->desejaEnviarZapGuilherme)) {
if($data->desejaEnviarZapGuilherme=='Sim') {
$messageBody = "Favor enviar a mercadoria pelos Correios. *Pedido Nº: $numeroPedido*" . "\n\n" .
"Acesse o card: https://polo.srvtmp.com.br/app-externo#$numeroPedido";
$this->sendMensagemViaWhatsapp('text', '5562993126267', $messageBody, null, null, null);
}
}
$contato = $data->contato;
$observacao = "";
$numeroPedido = ($entregaNova->getPedido()!='') ? $entregaNova->getPedido() : $entregaNova->getNotaFiscal();
if(isset($data->observacaoCadastro)){
$observacao = $data->observacaoCadastro;
}
if($observacao!='') {
// Envio zap benjamim
$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";
if($data->tipo=='pedido_entregue'){
$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";
}
} else {
// Envio zap benjamim
$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";
if($data->tipo=='pedido_entregue'){
$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;
}
}
$entregaNova->setCodidoRastreio($this->geraCodigoRastreio());
if($data->tipo!='mkplace') {
if($data->tipo!='pedido_entregue'){
$this->notificaClienteCriacaoCard($entregaNova);
}
//$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // Benjamim
//$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
$this->sendMensagemViaWhatsapp("text", "556291089053", $messageBody, null, null, null); // Bruno
//$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
//$this->sendMensagemViaWhatsapp("text", "5562981352530", $messageBody, null, null, null); // Mateus
}
if($data->tipo=='mkplace'){
$entregaNova->setStatus('baixado');
}
if($data->tipo=='pedido_entregue'){
$entregaNova->setStatus('entregue');
}
if(($data->meioEntrega=='Pela Pollo Móveis' || $data->meioEntrega=='Viagem pela Pollo Móveis')) {
if($enderecoEntregaParaGeocode!=''){
$coordenadasDoEndereco = $this->decodificaEndereco($enderecoEntregaParaGeocode);
if($coordenadasDoEndereco!==false){
if(isset($coordenadasDoEndereco['latitude']) && isset($coordenadasDoEndereco['longitude'])){
$entregaNova->setLatitude($coordenadasDoEndereco['latitude']);
$entregaNova->setLongitude($coordenadasDoEndereco['longitude']);
$linkEndereco = "https://waze.com/ul?ll=".$coordenadasDoEndereco['latitude'].",".$coordenadasDoEndereco['longitude']."&navigate=yes";
$entregaNova->setLinkEnderecoEntrega($linkEndereco);
$entregaNova->setEnderecoEntrega($enderecoEntregaParaGeocode);
}
}
}
}
$this->getDoctrine()->getManager()->flush();
$isUrgente = $urgente;
$clienteVaiBuscarImediatamente = false;
if(isset($data->entregarHoje)){
$clienteVaiBuscarImediatamente = ($data->entregarHoje=='Cliente Vai Retirar Imediatamente') ? true : false;
}
if(isset($data->montarMoveis)) {
if($data->montarMoveis=='Não') {
if($data->origemMontagem=='Galpão Coimbra') {
$this->createDemandaPedido($entregaNova, 'co', 'separacao', true, $clienteVaiBuscarImediatamente, $isUrgente);
} else if($data->origemMontagem=='Galpão São José') {
$this->createDemandaPedido($entregaNova, 'sj', 'separacao', true, $clienteVaiBuscarImediatamente, $isUrgente);
} else { // Galpão Coimbra/Galpão São José
$this->createDemandaPedido($entregaNova, 'co', 'separacao', true, $clienteVaiBuscarImediatamente, $isUrgente);
$this->createDemandaPedido($entregaNova, 'sj', 'separacao', true, $clienteVaiBuscarImediatamente, $isUrgente);
}
} else {
if($data->origemMontagem=='Galpão Coimbra'){
$this->createDemandaPedido($entregaNova, 'co', 'montagem', true, $clienteVaiBuscarImediatamente, $isUrgente);
} else if($data->origemMontagem=='Galpão São José') {
$this->createDemandaPedido($entregaNova, 'sj', 'montagem', true, $clienteVaiBuscarImediatamente, $isUrgente);
} else { // Galpão Coimbra/Galpão São José
$this->createDemandaPedido($entregaNova, 'co', 'montagem', true, $clienteVaiBuscarImediatamente, $isUrgente);
$this->createDemandaPedido($entregaNova, 'sj', 'montagem', true, $clienteVaiBuscarImediatamente, $isUrgente);
}
}
}
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
private function geraCodigoRastreio(){
$caracteres = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
$codigo = '';
for ($i = 0; $i < 12; $i++) {
$codigo .= $caracteres[rand(0, strlen($caracteres) - 1)];
}
return $codigo;
}
/**
* @Route("/app-externo/deletar-entrega", name="deletar_entrega", methods={"POST"})
*/
public function deletarPedido(Request $request): Response
{
if($this->getUser()->getEmail()!='bruno@moveispollo.com.br') {
return new JsonResponse(['message'=>'Não é possível excluir'], 400);
}
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$pedido instanceof EntregaPedido) {
return new JsonResponse([], 400);
}
if($pedido->getRoute()!=null){
return new JsonResponse($this->todosPedidosPorStatus(), 201);
}
$pedido->setDeletedAt(new \DateTime('now'));
//$this->getDoctrine()->getManager()->remove($pedido);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/informar-localizacao", name="informar_localizacao", methods={"POST"})
*/
public function informarLocalizacao(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
$pedido->setLocalizacao($data->localizacao);
if($data->localizacao=='limpar' || $data->localizacao=='apagar'){
$pedido->setLocalizacao(null);
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/informar-obs", name="informmar_obs", methods={"POST"})
*/
public function informarObs(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
$user = $this->getUser();
$pedido->setIsObsLida(false);
$dataHora = new \DateTime('now');
if($data->obs!="") {
$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>';
if($pedido->getObsVendedor() != '') {
$obs = $pedido->getObsVendedor() . ' - ' . $obs;
$pedido->setObsVendedor($obs);
} else {
$pedido->setObsVendedor($obs);
}
}
if(strtolower(trim($data->obs))=='limpar') {
$pedido->setObsVendedor('');
} else {
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
$linkPedido = 'https://polo.srvtmp.com.br/app-externo/busca-pedido-detalhe?p=' . $numeroPedido;
$messageBody =
"*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";
//$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // benjamim
//$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
$this->sendMensagemViaWhatsapp("text", "556291089053", $messageBody, null, null, null); // Bruno
//$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
if($pedido->getColaboradorUser()!='' && $pedido->getColaboradorUser()!=null) {
$telefoneMotorista = $pedido->getColaboradorUser()->getTelefone();
$this->sendMensagemViaWhatsapp("text", $telefoneMotorista, $messageBody, null, null, null);
}
if($pedido->getStatus()=='pendente' || $pedido->getStatus()=='recebido' || $pedido->getStatus()=='aceito'){
if($pedido->getSeparador()!='' && $pedido->getSeparador()!=null){
$usarioSeparador = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$pedido->getSeparador()]);
if($usarioSeparador instanceof User) {
$this->sendMensagemViaWhatsapp("text", $usarioSeparador->getTelefone(), $messageBody, null, null, null);
}
}
}
// Envio zap vendedor
$usuarioVendedor = strtolower($pedido->getVendedor());
$usarioVendedor = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioVendedor]);
if($usarioVendedor instanceof User){
$telefone = $usarioVendedor->getTelefone();
$destino = 'W';
if($telefone=='556232337424') {
$destino = 'B';
}
$this->sendMensagemViaWhatsapp("text", $telefone, $messageBody, null, null, null, $destino);
}
// Envio zap Cadastrante
$usuarioCadastrante = strtolower($pedido->getCadastradoPor());
$usuarioCadastrante = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$usuarioCadastrante]);
if($usuarioCadastrante instanceof User){
$telefone = $usuarioCadastrante->getTelefone();
$destino = 'W';
if($telefone=='556232337424') {
$destino = 'B';
}
$this->sendMensagemViaWhatsapp("text", $telefone, $messageBody, null, null, null, $destino);
}
}
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/informar-tratativa", name="informmar_tratativa", methods={"POST"})
*/
public function informarTratativa(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
$pedido->setTratativa($data->tratativa);
$this->getDoctrine()->getManager()->flush();
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
/**
* @Route("/app-externo/informar-problema", name="informmar_problema", methods={"POST"})
*/
public function informarProblema(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
$todosPedidos = (!$this->getUser() instanceof User) ? [] : $this->todosPedidosPorStatus();
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($todosPedidos, 201);
}
// É para manter os dados de problema no card original?
$pedidoENF = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['notaFiscal'=>$pedido->getPedido(),'deletedAt'=>null]);
if(!$pedidoENF instanceof EntregaPedido){
$pedidoExistente = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido'=>$pedido->getPedido().'-Assistência', 'deletedAt'=>null]);
if($pedidoExistente instanceof EntregaPedido) {
return new JsonResponse($todosPedidos, 201);
}
}
$dataPedidoEntrega = \DateTime::createFromFormat('Y-m-d', $data->data_entrega_assistencia);
$novoPedido = clone $pedido;
//$novoPedido->setId(null);
$novoPedido->setPedido($pedido->getPedido().'-Assistência');
$novoPedido->setProblema($data->problema);
$novoPedido->setProblemaObs($data->obs);
$novoPedido->setStatus('pendente');
$novoPedido->setCreatedAt(new \DateTime('now'));
$novoPedido->setUpdatedAt(new \DateTime('now'));
$usuarioNome = (!$this->getUser() instanceof User) ? 'Acesso público' : $this->getUser()->getNome();
$novoPedido->setCadastradoPor($usuarioNome);
if($data->problema=='COLETA REVERSA') {
$novoPedido->setReversaNomeCliente($data->reversa_nome_cliente);
$novoPedido->setReversaContatoCliente($data->reversa_contato_cliente);
$novoPedido->setReversaEndereco($data->reversa_endereco);
$novoPedido->setReversaVolume($data->reversa_volume);
$novoPedido->setMercadoriaEmbalada($data->reversa_embalada);
}
if($data->problema=='DEVOLUCAO DE VALORES') {
$valor = preg_replace("/[^0-9,.]/", "", $data->devolucao_de_valores__valor_extorno);
$valor = str_replace(".", "", $valor);
$valor = str_ireplace(',','.', $valor);
$novoPedido->setDevolucaoValoresForma($data->devolucao_de_valores__forma_extorno);
$novoPedido->setDevolucaoValoresValor($valor);
$novoPedido->setDevolucaoValoresMotivo($data->devolucao_de_valores__motivo_extorno);
$novoPedido->setDevolucaoValoresChavePix($data->devolucao_de_valores__chave_pix_extorno);
$dataDevolucaoValores = explode('-', $data->devolucao_de_valores__data_pagamento_cliente_extorno);
$novoPedido->setDevolucaoValoresDataCliente("{$dataDevolucaoValores[2]}/{$dataDevolucaoValores[1]}/{$dataDevolucaoValores[0]}");
}
$novoPedido->setBaixadoAt(null);
$novoPedido->setSeparadorAceitouAt(null);
$novoPedido->setTempoGastoSeparacao(null);
$novoPedido->setColaboradorUser(null);
$novoPedido->setPedidoRealizadoCheckAt(null);
$novoPedido->setPedidoRealizadoCoimbraCheckAt(null);
$novoPedido->setPedidoImpressoCheckAt(null);
$novoPedido->setPedidoEnderecoCheckAt(null);
$novoPedido->setPedidoMontagemCheckAt(null);
$novoPedido->setPedidoMotoristaCheckAt(null);
$novoPedido->setPedidoInstagramCheckAt(null);
$novoPedido->setPedidoGoogleCheckAt(null);
$novoPedido->setPedidoMontandoMontagemFinalizada(null);
$novoPedido->setPedidoMontandoRonald(null);
$novoPedido->setAguardandoColeta(null);
$novoPedido->setIsColetado(null);
$novoPedido->setDataLimiteParado(null);
$novoPedido->setPedidoImpressoCheckAtSaoJose(null);
$novoPedido->setPedidoImpressoGuilhermeCheck(null);
$novoPedido->setPedidoPagoCheckAtSaoJose(null);
$novoPedido->setPedidoRetiradoCheckAtSaoJose(null);
$novoPedido->setPedidoCeletadoCheckAtSaoJose(null);
$novoPedido->setPedidoFotoProdutoCheckAtSaoJose(null);
$novoPedido->setPedidoFotoAssinaturaCheckAtSaoJose(null);
$novoPedido->setPedidoPagoCheckAt(null);
$novoPedido->setPedidoMontandoFabio(null);
$novoPedido->setPedidoMontandoRian(null);
$novoPedido->setSolicitarMontagem(null);
$novoPedido->setSolicitarMontagemSaoJose(null);
$novoPedido->setSolicitarSeparacao(null);
$novoPedido->setSolicitarSeparacaoSaoJose(null);
$novoPedido->setDataInicioEntrega(null);
$novoPedido->setDataInicioEntrega(null);
$novoPedido->setAceitoAt(null);
$novoPedido->setObsVendedor(null);
$novoPedido->setObservacaoCadastro(null);
$novoPedido->setLinkEnderecoEntrega(null);
$novoPedido->setRoute(null);
$novoPedido->setEntregarAt(null);
$novoPedido->setIsEntregue(false);
$novoPedido->setAuxiliar('');
$novoPedido->setFotos(null);
$novoPedido->setNotas(null);
$novoPedido->setFotosSinistro(null);
$novoPedido->setFotosAssistencia(null);
$novoPedido->setComprovantePagamento(null);
$novoPedido->setSeparador(null, true);
if($dataPedidoEntrega instanceof \DateTime) {
$novoPedido->setDataEntrega($dataPedidoEntrega);
}
$novoPedido->setIsAssistencia(true);
$novoPedido->setLastUpdateStatus(new \DateTime('now'));
$this->getDoctrine()->getManager()->persist($novoPedido);
$this->getDoctrine()->getManager()->flush();
/*
$pedido->setProblema($data->problema);
$pedido->setProblemaObs($data->obs);
$pedido->setStatus('pendente');
//$pedido->setCreatedAt(new \DateTime('now'));
$pedido->setUpdatedAt(new \DateTime('now'));
$this->getDoctrine()->getManager()->flush();
*/
$numeroPedido = ($novoPedido->getPedido()!='') ? $novoPedido->getPedido() : $novoPedido->getNotaFiscal();
// Caso COLETA REVERSA
if($data->problema=='COLETA REVERSA') {
$nomeCliente = $novoPedido->getReversaNomeCliente();
$contatoCliente = $novoPedido->getReversaContatoCliente();
$enderecoColeta = $novoPedido->getReversaEndereco();
$volume = $novoPedido->getReversaVolume();
$embalado = $novoPedido->getMercadoriaEmbalada();
$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";
//$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
} else if($data->problema=='DEVOLUCAO DE VALORES'){
$devolucao_de_valores__forma_extorno = $novoPedido->getDevolucaoValoresForma();
$devolucao_de_valores__valor_extorno = number_format($novoPedido->getDevolucaoValoresValor(), 2, ',', '.');
$devolucao_de_valores__motivo_extorno = $novoPedido->getDevolucaoValoresMotivo();
$devolucao_de_valores__chave_pix_extorno = $novoPedido->getDevolucaoValoresChavePix();
$devolucao_de_valores__data_pagamento_cliente_extorno = $novoPedido->getDevolucaoValoresDataCliente();
$messageBody = "*ATENÇÃO*\n\n*SOLICITAÇÃO DE DEVOLUÇÃO DE VALORES.*";
$dados = "\n\n*Motivo:* DEVOLUÇÃO DE VALORES";
$dados .= "\n\n*Pedido/NF:* $numeroPedido";
$dados .= "\n\n*Cliente:* {$novoPedido->getContato()}";
$dados .= "\n\nForma de devolução: $devolucao_de_valores__forma_extorno";
$dados .= "\n\nValor da devolução: $devolucao_de_valores__valor_extorno";
if($devolucao_de_valores__forma_extorno=='Outros') {
$dados .= "\n\nChave pix da devolução: $devolucao_de_valores__chave_pix_extorno";
}
$dados .= "\n\nMotivo da devolução: $devolucao_de_valores__motivo_extorno";
$dados .= "\n\n*Outras observações:* {$data->obs}\n";
$dados .= "\n\nData do pagamento: $devolucao_de_valores__data_pagamento_cliente_extorno";
$messageBody .= $dados;
$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // benjamim
//$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
$this->sendMensagemViaWhatsapp("text", "556291089053", $messageBody, null, null, null); // Bruno
//$this->sendMensagemViaWhatsapp("text", "5562983281823", $messageBody, null, null, null); // Bruno P
//$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
} else {
$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";
//$this->sendMensagemViaWhatsapp("text", "5562992933530", $messageBody, null, null, null); // benjamim
//$this->sendMensagemViaWhatsapp("text", "5562993126267", $messageBody, null, null, null); // Guilherme
//$this->sendMensagemViaWhatsapp("text", "556291089053", $messageBody, null, null, null); // Bruno
//$this->sendMensagemViaWhatsapp("text", "5562993365412", $messageBody, null, null, null); // Junior
}
return new JsonResponse($todosPedidos, 200);
}
/**
* @Route("/app-externo/informar-auxiliar", name="informmar_auxiliar", methods={"POST"})
*/
public function informarAuxiliar(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
$user = $this->getUser();
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
$pedidoAssistencia = strpos($pedido->getPedido(), "Assistência");
if(!$this->getIsAdmin() && $pedidoAssistencia!==false){
return new JsonResponse([], 201);
}
if($this->getIsEntregadorAux()) {
$pedido->setAuxiliar($user->getEmail());
$this->getDoctrine()->getManager()->flush();
}
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
public function criaRotaEAdicionaPedido($pedido, $user=null) {
if($this->getUser() instanceof User){
if($user==null){
$user = $this->getUser();
}
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
$rota = $this->getDoctrine()->getRepository(EntregaRoute::class)->findOneBy(['titulo'=>$user->getEmail()]);
if($rota instanceof EntregaRoute){
$pedidos = $rota->getPedidos();
if($pedidos===null || $pedidos===''){
$rota->setPedidos($numeroPedido);
} else {
$pedidos = explode(',', $pedidos);
if(!in_array($numeroPedido, $pedidos)){
if(!empty($numeroPedido)){
$pedidos[] = $numeroPedido;
}
}
$rota->setPedidos(implode(',', $pedidos));
}
$pedido->setRoute($rota);
$this->getDoctrine()->getManager()->flush();
}
}
// $numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
// // Verifica se já
// $rota = new EntregaRoute();
// $rota->setTitulo($user->getNome());
// $rota->setIsFinish(false);
// $rota->setCreatedAt(new \DateTime());
// $rota->setDataEntrega($pedido->getDataEntrega());
// $rota->setPedidos($numeroPedido);
// $this->getDoctrine()->getManager()->persist($rota);
// $this->getDoctrine()->getManager()->flush();
// $pedido->setRoute($rota);
// $this->getDoctrine()->getManager()->flush();
}
/**
* @Route("/app-externo/informar-motorista", name="informmar_motorista", methods={"POST"})
*/
public function informarMotorista(Request $request): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
$user = $this->getUser();
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
$pedidoAssistencia = strpos($pedido->getPedido(), "Assistência");
if(!$this->getIsAdmin() && $pedidoAssistencia!==false){
return new JsonResponse(['message'=>'Você não pode informar motorista em cartão de Assistência.'], 201);
}
$isAuxiliar = filter_var($data->isAuxiliar, FILTER_VALIDATE_BOOLEAN);
if(!$this->getIsAdmin()){
if($this->getIsEntregador()) {
if($pedido->getColaboradorUser() instanceof User){
return new JsonResponse(['message'=>'Proibido alterar motorista em andamento. Fale com o gerenciador'], 201);
}
} else if($isAuxiliar) {
if($pedido->getAuxiliar()!='' && $pedido->getAuxiliar()!=null){
return new JsonResponse(['message'=>'Proibido alterar motorista em andamento. Fale com o gerenciador'], 201);
}
}
}
//if(!$isAuxiliar) {
if($this->getIsEntregador()) {
if(!$pedido->getColaboradorUser() instanceof User){
$pedido->setStatus('aceito');
$pedido->setLastUpdateStatus(new \DateTime('now'));
$this->criaRotaEAdicionaPedido($pedido, null);
} else {
return new JsonResponse([], 202);
}
} else {
$pedido->setStatus('aceito');
$pedido->setLastUpdateStatus(new \DateTime('now'));
$this->criaRotaEAdicionaPedido($pedido, null);
}
//}
if($this->getIsEntregadorAux()) {
//$pedido->setAuxiliar($user->getEmail());
$usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
// if(!$data->atendente){
// $usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$user->getEmail()]);
// } else {
// $usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
// }
if(!$usuarioSelecionado instanceof User){
return new JsonResponse([], 400);
}
$pedido->setColaboradorUser($usuarioSelecionado);
} else {
if($data->isAuxiliar==1){
if(!$data->atendente){
$pedido->setAuxiliar($user->getEmail());
} else {
$pedido->setAuxiliar($data->atendente);
}
//$usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
} else {
if(!$data->atendente){
$usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$user->getEmail()]);
} else {
$usuarioSelecionado = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
}
if(!$usuarioSelecionado instanceof User){
return new JsonResponse([], 400);
}
$pedido->setColaboradorUser($usuarioSelecionado);
}
}
$pedido->setAceitoAt(new \DateTime());
// Faz um lancamentos
if($pedido->getMeioEntrega()=='Viagem pela Pollo Móveis') {
if($data->isAuxiliar==1){
if(!$data->atendente){
$usuarioAuxiliar = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$user->getEmail()]);
} else {
$usuarioAuxiliar = $this->getDoctrine()->getRepository(User::class)->findOneBy(['email'=>$data->atendente]);
}
if($usuarioAuxiliar instanceof User) {
// $descricao = "Viagem pela Pollo Móveis - Pedido {$pedido->getPedido()} - Endereço: {$pedido->getEndereco()}";
// $lancamentoNovo = $this->getDoctrine()->getRepository(LancamentoFinanceiroColaborador::class)
// ->findOneBy(['colaborador'=>$usuarioAuxiliar, 'descricao'=>$descricao]);
// if(!$lancamentoNovo instanceof LancamentoFinanceiroColaborador){
// $lancamento = new LancamentoFinanceiroColaborador();
// $lancamento->setColaborador($usuarioAuxiliar);
// $lancamento->setTipo('credito');
// $lancamento->setValor(120);
// $lancamento->setData(new \DateTime());
// $lancamento
// ->setDescricao($descricao);
// $this->getDoctrine()->getManager()->persist($lancamento);
// $this->getDoctrine()->getManager()->flush();
// }
}
} else {
$descricao = "Viagem pela Pollo Móveis - Pedido {$pedido->getPedido()} - Endereço: {$pedido->getEndereco()}";
// $lancamentoNovo = $this->getDoctrine()->getRepository(LancamentoFinanceiroColaborador::class)
// ->findOneBy(['colaborador'=>$usuarioAuxiliar, 'descricao'=>$descricao]);
// if(!$lancamentoNovo instanceof LancamentoFinanceiroColaborador){
// $lancamento = new LancamentoFinanceiroColaborador();
// $lancamento->setColaborador($usuarioSelecionado);
// $lancamento->setTipo('credito');
// $lancamento->setValor(220);
// $lancamento->setData(new \DateTime());
// $lancamento
// ->setDescricao($descricao);
// $this->getDoctrine()->getManager()->persist($lancamento);
// $this->getDoctrine()->getManager()->flush();
// }
}
}
$pedido->setLastUpdateStatus(new \DateTime('now'));
$this->getDoctrine()->getManager()->flush();
$todosPedios = [];
if($this->getUser() instanceof User){
$todosPedios = $this->todosPedidosPorStatus();
}
return new JsonResponse($todosPedios, 200);
}
/**
* @Route("/app-externo/informar-status", name="informmar_estatus", methods={"POST"})
*/
public function entregarPedidos(Request $request, LogAcoesService $logAcoesService, EntityManagerInterface $entityManager): Response
{
$data = json_decode($request->getContent(), false);
$pedido = $this->getDoctrine()->getRepository(EntregaPedido::class)->find($data->pedido);
$origem = $this->getStatusCorretoNome($pedido->getStatus());
if(!$pedido instanceof EntregaPedido){
return new JsonResponse($pedidosData, 400);
}
if($data->status == 'transito'){
if($this->getIsEntregador()){
$pedidosEmTransito = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['status'=>'transito', 'colaboradorUser'=>$this->getUser(), 'deletedAt'=>null]);
if(count($pedidosEmTransito)>0){ // Tem algum pedido em transito
$pedidosEmTransitoPendentes = [];
foreach ($pedidosEmTransito as $pedido){
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
$pedidosEmTransitoPendentes[] = $numeroPedido;
}
return new JsonResponse(['status'=>400, 'pedidos'=>implode(', ', $pedidosEmTransitoPendentes)], 200);
}
}
}
if($data->status == 'entregue'){
if($pedido->getFotos()!='' && $pedido->getNotas()!=''){
$pedido->setStatus($data->status);
$pedido->setEntregarAt(new \DateTime());
// Remove esse pedido das rotas
$this->removePedidoRota($pedido);
} else {
return new JsonResponse($pedidosData, 401);
}
} else {
$pedido->setStatus($data->status);
}
if($data->status == 'aceito'){
$pedidoAssistencia = strpos($pedido->getPedido(), "Assistência");
if(!$this->getIsAdmin() && $pedidoAssistencia!==false){
return new JsonResponse([], 201);
}
if($pedido->getMeioEntrega()=='Viagem pela Pollo Móveis') {
// $descricao = "Viagem pela Pollo Móveis - Pedido {$pedido->getPedido()} - Endereço: {$pedido->getEndereco()}";
// $lancamentoNovo = $this->getDoctrine()->getRepository(LancamentoFinanceiroColaborador::class)
// ->findOneBy(['colaborador'=>$this->getUser(), 'descricao'=>$descricao]);
// if(!$lancamentoNovo instanceof LancamentoFinanceiroColaborador){
// $lancamento = new LancamentoFinanceiroColaborador();
// $lancamento->setColaborador($this->getUser());
// $lancamento->setTipo('credito');
// $lancamento->setValor(220);
// $lancamento->setData(new \DateTime());
// $lancamento->setDescricao($descricao);
// $this->getDoctrine()->getManager()->persist($lancamento);
// $this->getDoctrine()->getManager()->flush();
// }
}
$pedido->setColaboradorUser($this->getUser());
$pedido->setAceitoAt(new \DateTime());
}
if($data->status == 'baixado'){
$pedido->setBaixadoAt(new \DateTime());
}
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
$tipoPedido = ($pedido->getPedido()!='') ? '' : ' - NF';
if($data->status == 'transito'){
if($this->getIsEntregadorAux()) {
$pedido->setAuxiliar($this->getUser()->getEmail());
} else {
$user = $this->getUser();
if ($user) {
if($pedido->getColaboradorUser()->getId()!=$this->getUser()->getId() && !$this->getIsAdmin()){
return new JsonResponse([], 400);
}
}
}
$pedido->setDataInicioEntrega(new \DateTime('now'));
$motorista = $pedido->getColaboradorUser()->getNome();
$motoristaTel = $pedido->getColaboradorUser()->getTelefone();
$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;
$messageImagemBody = 'entrega.jpeg?v=12';
$messageImagemBody = 'https://polo.srvtmp.com.br/frontend/images-notificacoes-trello/' . $messageImagemBody . '?v='.time();
$type = 'img';
// $this->sendMensagemViaWhatsapp($type, $pedido->getTelefone(), $messageBody, $messageImagemBody, null, null);
$numeroTelefone = $pedido->getTelefone();
$telefones = explode('|', $numeroTelefone);
if(count($telefones)>1){
if($telefones[0]!=$telefones[1]){
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
$this->sendMensagemViaWhatsapp($type, $telefones[1], $messageBody, $messageImagemBody, null, null);
} else {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
}
} else {
$this->sendMensagemViaWhatsapp($type, $telefones[0], $messageBody, $messageImagemBody, null, null);
}
}
$pedido->setLastUpdateStatus(new \DateTime('now'));
$this->getDoctrine()->getManager()->flush();
$status = $this->getStatusCorretoNome($data->status);
// $numeroPedido .= $tipoPedido;
// $logAcoesService
// ->registraAcao(
// $entityManager,
// $this->getUser(),
// 'Mudança de status para: ' . $status,
// $numeroPedido,
// 'O card veio de: ' . $origem
// );
$todosPedidos = [];
if($this->getUser() instanceof User) {
return new JsonResponse($this->todosPedidosPorStatus(), 200);
}
return new JsonResponse($todosPedidos, 200);
}
private function removePedidoRota($pedido) {
if($pedido->getRoute() instanceof EntregaRoute){
$numeroPedido = ($pedido->getPedido()!='') ? $pedido->getPedido() : $pedido->getNotaFiscal();
// Converte a string em um array
$array = explode(',', $pedido->getRoute()->getPedidos());
// Procura o índice do pedido que você quer remover
$indice = array_search($numeroPedido, $array);
// Se o pedido for encontrado, remove do array
if ($indice !== false) {
unset($array[$indice]);
}
// Reconverte o array de volta para uma string
$stringAtualizada = implode(',', $array);
$pedido->getRoute()->setPedidos($stringAtualizada);
$this->getDoctrine()->getManager()->flush();
}
// $rotas = $this->getDoctrine()->getRepository(EntregaRoute::class)->findByPedido($numeroPedido);
// if(count($rotas)>0){
// foreach ($rotas as $rota){
// // Converte a string em um array
// $array = explode(',', $rota->getPedidos());
// // Procura o índice do pedido que você quer remover
// $indice = array_search($numeroPedido, $array);
// // Se o pedido for encontrado, remove do array
// if ($indice !== false) {
// unset($array[$indice]);
// }
// // Reconverte o array de volta para uma string
// $stringAtualizada = implode(',', $array);
// $rota->setPedidos($stringAtualizada);
// }
// }
}
/**
* @Route("/app-externo/lista-pedidos", name="lista_app_externo", methods={"POST"})
*/
public function listaPedidos(Request $request): Response
{
$data = json_decode($request->getContent(), false);
return new JsonResponse($this->todosPedidosPorStatus($data->pedidoFiltrado, $data->field), 200);
}
private function getPedidos($status, $busca=false) {
$user = $this->getUser();
$pedidosData = [];
$hoje = new \DateTime();
$user = $this->getUser();
if($status!='pendente' && $status!='recebido') {
if($status=='baixado') {
if(!$busca){
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['deletedAt'=>null, 'status'=>$status], array('updatedAt' => 'DESC'), 10, 0);
} else {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['deletedAt'=>null, 'status'=>$status], array('updatedAt' => 'DESC'));
}
} else {
if($status!='pendente') {
// Veriicar se é super admin
if($this->getIsAdmin() || $this->getIsVendedor()) {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null, 'status'=>$status], array('updatedAt' => 'DESC'));
} else {
if($this->getIsEntregadorAux()){
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'deletedAt'=>null, 'status'=>$status, 'auxiliar'=>$user->getEmail()], array('updatedAt' => 'DESC'));
} else {
// $pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'status'=>$status], array('id' => 'DESC'));
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null, 'status'=>$status, 'colaboradorUser'=>$user], array('updatedAt' => 'DESC'));
}
}
} else {
// Veriicar se é super admin
if($this->getIsAdmin() || $this->getIsVendedor()) {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null, 'status'=>$status], array('updatedAt' => 'DESC'));
} else {
if($this->getIsEntregadorAux()){
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'deletedAt'=>null, 'status'=>$status, 'auxiliar'=>$user->getEmail()], array('updatedAt' => 'DESC'));
} else {
// $pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'status'=>$status], array('id' => 'DESC'));
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null,'deletedAt'=>null, 'status'=>$status, 'colaboradorUser'=>$user], array('updatedAt' => 'DESC'));
}
}
}
}
} else {
// Se for pendente todos podem ver
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->findBy(['baixadoAt'=>null, 'deletedAt'=>null, 'status'=>$status], array('updatedAt' => 'DESC'));
}
foreach ($pedidos as $pedido) {
// $obsVendedorStr = '';
// $obsVendedor = explode('-', $pedido->getObsVendedor());
// if(count($obsVendedor)>0) {
// foreach ($obsVendedor as $obsVendedorStrItem) {
// $obsVendedorStr .= '<div class="blink_me badge-pollo">'.strip_tags($obsVendedorStrItem).'</div>';
// }
// } else {
// $obsVendedorStr = $obsVendedor;
// }
// Pular pedidos deletados
if($pedido->getDeletedAt()!=null && $pedido->getDeletedAt()!='') {
continue;
}
$pedidosData[] = $this->makeProdutoData($pedido);
}
return $pedidosData;
}
public function isDonoPedido($pedido) {
if(!$pedido->getColaboradorUser()){
return false;
}
if(!$this->getUser() instanceof User){
return false;
}
// if(!$pedido->getColaboradorUser() instanceof User ||
// !$this->getUser() instanceof User ||
// !$pedido->getAuxiliar()==$this->getUser() instanceof User){
// return false;
// }
return ($pedido->getColaboradorUser()->getId() == $this->getUser()->getId() || $pedido->getAuxiliar()==$this->getUser()->getEmail());
}
private function getPedido($numero, $client, $tipoPedido='pedido', $pedidoMake=null) {
$response = $client->request(
'GET',
SincronizacaoController::URL_API_BLING . '/pedido/'.$numero.'/json/',
[
'query' => [
'apikey' => SincronizacaoController::KEY_API_POLLO
]
]
);
$statusCode = $response->getStatusCode();
$numeroNota = '';
$dados = [
'telefone' =>'',
'endereco' => '',
'endereco_entrega' => '',
'tipo' => $tipoPedido,
'numeroNf' => '',
'numeroPedido' => $numero,
'isUrgente' => 'Não',
'assistencia' => 'Não',
'contato' => '',
'periodosEntrega' => '',
'entregarHoje' => '',
'vendedor' => '',
'embalagem' => 'Desmontado',
'exigeLadoBalcao' => false, // Qual lado do balcão
'cnpj' => '',
'frete' =>'',
'solicitarColeta' => '',
'nomeTrasportadora' => '',
'meioEntrega' => '',
'esperarClientePagar' => 'Não',
'cotarFrete' => '',
'itens' => '',
'dataAgendamentoEntrega' => ''
];
if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
$content = $response->toArray();
if(isset($content['retorno'])){
if(isset($content['retorno']['pedidos'])){
if(count($content['retorno']['pedidos']) > 0) {
if(isset($content['retorno']['pedidos'][0])){
$pedido = $content['retorno']['pedidos'][0]['pedido'];
if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'])){
$dados['endereco'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['numero'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['complemento'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['bairro'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['cidade'] . '/' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['uf'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['cep'] . ', ';
}
$dados['contato'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['nome'];
$telefones = [];
if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['celular'])){
if($content['retorno']['pedidos'][0]['pedido']['cliente']['celular']!=""){
$telefone = $content['retorno']['pedidos'][0]['pedido']['cliente']['celular'];
$telefone = '55'.$telefone;
$telefones[] = preg_replace('/\D/', '', $telefone);
}
}
if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['fone'])){
if($content['retorno']['pedidos'][0]['pedido']['cliente']['fone']!=""){
$telefone = $content['retorno']['pedidos'][0]['pedido']['cliente']['fone'];
$telefone = '55'.$telefone;
$telefones[] = preg_replace('/\D/', '', $telefone);
}
}
$dados['telefone'] = implode('|', $telefones);
if(isset($content['retorno']['pedidos'][0]['pedido']['nota'])){
$dados['numeroNf'] = intval($content['retorno']['pedidos'][0]['pedido']['nota']['numero']);
}
$dados['vendedor'] = $content['retorno']['pedidos'][0]['pedido']['vendedor'];
$dados['cnpj'] = '';
$dados['totalvenda'] = '';
$dados['itens'] = [];
if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['cnpj'])){
$dados['cnpj'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['cnpj'];
}
$dataPedido = \DateTime::createFromFormat('Y-m-d', $content['retorno']['pedidos'][0]['pedido']['data']);
$dados['data'] = $dataPedido->format('d/m/Y');
$totalItens = 0;
$totalItensTotal = 0;
$valorSubTotal = 0;
$descontosItens = 0;
if(!empty($content['retorno']['pedidos'][0]['pedido']['itens'])){
foreach ($content['retorno']['pedidos'][0]['pedido']['itens'] as $item) {
if(in_array($item['item']['codigo'], $this->skusDebalcao())){
$dados['exigeLadoBalcao'] = true;
}
$totalItens++;
$valorTotal = $item['item']['quantidade'] * $item['item']['valorunidade'];
$valorSubTotal += $valorTotal;
$totalItensTotal += $item['item']['quantidade'];
$descontosItens += $item['item']['descontoItem'];
$img = '';
$pathFile = '/www/wwwroot/gestor.moveispollo.com.br/public/uploads/produtos/' . $item['item']['codigo'] . '.jpg';
if(file_exists($pathFile)){
$img = 'https://polo.srvtmp.com.br/uploads/produtos/' . $item['item']['codigo'] . '.jpg';
} else {
$produtoBling = $this->getProduto(SincronizacaoController::KEY_API_POLLO,
$item['item']['codigo'], $client, $xml=false);
if(isset($produtoBling['retorno']['produtos'][0])) {
if(isset($produtoBling['retorno']['produtos'][0]['produto']['imagem'][0])) {
$img = $produtoBling['retorno']['produtos'][0]['produto']['imagem'][0]['link'];
$img = str_ireplace('\\','',$img);
}
}
}
$dados['itens'][] = [
'codigo' => $item['item']['codigo'],
'descricao' => $item['item']['descricao'],
'un' => $item['item']['un'],
'quantidade' => abs($item['item']['quantidade']),
'valorunidade' => number_format($item['item']['valorunidade'], 2, ',', '.'),
'valorTotal' => number_format($valorTotal, 2, ',', '.'),
'img' => $img,
'estruturas' => $this->getEstruturas($item['item']['codigo']) // Primeiro nivel
];
}
}
$dados['parcelas'] = [];
if(!empty($content['retorno']['pedidos'][0]['pedido']['parcelas'])) {
foreach ($content['retorno']['pedidos'][0]['pedido']['parcelas'] as $parcela) {
$dataVencimento = \DateTime::createFromFormat('Y-m-d', $parcela['parcela']['dataVencimento']);
$dados['parcelas'][] = [
'valor' => number_format($parcela['parcela']['valor'], 2, ',', '.'),
'dias' => '0',
'dataVencimento' => $dataVencimento->format('d/m/Y'),
'formaPagamento' => $parcela['parcela']['forma_pagamento']['descricao'],
'obs' => $parcela['parcela']['obs']
];
}
}
$dados['numero_itens'] = $totalItens;
$dados['numero_itens_total'] = $totalItensTotal;
$dados['descontos'] = number_format($descontosItens, 2, ',', '.');
$dados['valorTotalPedido'] = number_format($valorSubTotal, 2, ',', '.');
$dados['valorTotalComDesconto'] = number_format($content['retorno']['pedidos'][0]['pedido']['totalvenda'], 2, ',', '.');
$dados['obs'] = $content['retorno']['pedidos'][0]['pedido']['observacoes'];
$dados['frete'] = (isset($content['retorno']['pedidos'][0]['pedido']['valorfrete'])) ? $content['retorno']['pedidos'][0]['pedido']['valorfrete'] : '';
$dados['descontoGeral'] = $content['retorno']['pedidos'][0]['pedido']['desconto'];
$pedidoEntrega = $this->getDoctrine()->getRepository(EntregaPedido::class)->findOneBy(['pedido' => $numero]);
$dados['showMaisPedidos'] = false;
$dados['estruturas'] = $this->agrupaEstruturas($dados['itens']);
if($pedidoEntrega instanceof EntregaPedido){
if($pedidoMake instanceof EntregaPedido){
$dados['mais_info'] = $this->makeProdutoData($pedidoMake, true);
} else {
$dados['mais_info'] = $this->makeProdutoData($pedidoEntrega, true);
}
$dados['showMaisPedidos'] = true;
}
if(!empty($content['retorno']['pedidos'][0]['pedido']['transporte'])){
if(!empty($content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega'])){
$dados['endereco_entrega'] =
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['endereco'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['numero'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['complemento'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['bairro'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['cidade'] . '/' .
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['uf'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['transporte']['enderecoEntrega']['cep'] . ', ';
}
}
//print_r($dados['itens']); exit;
return $dados;
}
}
}
}
} else {
exit('Erro em bucar pedido: ' . $numero);
}
return false;
}
public function agrupaEstruturas($itens) {
$estruturas = [];
foreach ($itens as $item) {
if(isset($item['estruturas']) && !empty($item['estruturas'])){
foreach ($item['estruturas'] as $estrutura) {
$produtoBling = $this->getDoctrine()->getRepository(ProdutoBling::class)->findOneBy(['codigo' => $estrutura->codigo]);
if(!$produtoBling instanceof ProdutoBling){
continue;
}
$isSimples = false;
if($produtoBling->getIsSimples()){
$isSimples = $produtoBling->getIsSimples();
}
$quantidade = $estrutura->quantidade * $item['quantidade'];
$estruturas[] = [
'nome' => $estrutura->nome,
'codigo' => $estrutura->codigo,
'quantidade' => $quantidade,
'isSimples' => $isSimples
];
}
}
}
$itensAgrupados = array();
// Iterar sobre os itens originais
foreach ($estruturas as $item) {
$codigo = $item["codigo"];
$quantidade = $item["quantidade"];
// Se o código já existir no array $itensAgrupados, adicione a quantidade
if (isset($itensAgrupados[$codigo])) {
$itensAgrupados[$codigo]["quantidade"] += $quantidade;
} else {
// Se não, crie uma nova entrada no array
$itensAgrupados[$codigo] = array(
"nome" => $item["nome"],
"codigo" => $codigo,
"quantidade" => $quantidade,
'isSimples' => $item["isSimples"]
);
}
}
// Resultado final com itens agrupados e quantidades somadas
$resultadoFinal = array_values($itensAgrupados);
return $resultadoFinal;
}
public function getEstruturas($codigo){
$produtoBling = $this->getDoctrine()->getRepository(ProdutoBling::class)->findOneBy(['codigo' => $codigo]);
if($produtoBling instanceof ProdutoBling) {
$estruturas = json_decode($produtoBling->getEstrutura());
if(!empty($produtoBling->getEstrutura())){
foreach ($estruturas as $estrutura){ // Pego para cada item uma estrutura dentro
$subEstruturas = $this->getSubEstruturas($estrutura->codigo);
if(!empty($subEstruturas)){
foreach ($subEstruturas as $subEstrutura){
$estruturas[] = $subEstrutura;
}
}
}
return (count($estruturas)>0) ? $estruturas : '';
}
return '';
}
return '';
}
public function getSubEstruturas($codigo) {
$produtoBling = $this->getDoctrine()->getRepository(ProdutoBling::class)->findOneBy(['codigo' => $codigo]);
if($produtoBling instanceof ProdutoBling) {
$estruturas = json_decode($produtoBling->getEstrutura());
if(!empty($produtoBling->getEstrutura())){
return (count($estruturas)>0) ? $estruturas : '';
}
return '';
}
return '';
}
private function getNotaFiscal($numero, $client, $tipoPedido) {
$response = $client->request(
'GET',
SincronizacaoController::URL_API_BLING . '/notafiscal/'.$numero.'/1/json/',
[
'query' => [
'apikey' => SincronizacaoController::KEY_API_POLLO
]
]
);
$dados = [
'telefone' =>'',
'endereco' => '',
'tipo' => $tipoPedido,
'numeroNf' => $numero,
'numeroPedido' => '',
'isUrgente' => 'Não',
'assistencia' => 'Não',
'contato' => '',
'periodosEntrega' => '',
'entregarHoje' => '',
'vendedor' => '',
'embalagem' => 'Desmontado',
'exigeLadoBalcao' => false, // Qual lado do balcão
'cnpj' => '',
'solicitarColeta' => '',
'nomeTrasportadora' => '',
'meioEntrega' => '',
'cotarFrete' => '',
'esperarClientePagar' => 'Não',
'dataAgendamentoEntrega' => ''
];
$statusCode = $response->getStatusCode();
if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
$content = $response->toArray();
if(isset($content['retorno'])){
if(isset($content['retorno']['notasfiscais'])){
if(count($content['retorno']['notasfiscais']) > 0) {
$notafiscal = $content['retorno']['notasfiscais'][0]['notafiscal'];
$data = explode(' ',$notafiscal['dataEmissao']);
$data = explode('-',$data[0]);
$keyNota = $notafiscal['chaveAcesso'];
//$url = 'https://www.bling.com.br/relatorios/nfe.xml.php?s&chaveAcesso=' . $keyNota;
$url = $notafiscal['xml'];
$url = str_replace("\\", "/", $url);
$xmlNota = simplexml_load_file($url);
//$xmlNota->NFe->infNFe->cobr->fat->vLiq
$trasportadora = 'A retirar';
if(isset($xmlNota->NFe->infNFe->transp)){
if(isset($xmlNota->NFe->infNFe->transp->transporta)){
$trasportadora = $xmlNota->NFe->infNFe->transp->transporta->xNome;
}
}
// $telefone = '';
// if(isset($notafiscal['cliente']['celular'])){
// if($notafiscal['cliente']['celular']!=""){
// $telefone = $notafiscal['cliente']['celular'];
// }
// } else if(isset($notafiscal['cliente']['fone'])){
// if($notafiscal['cliente']['fone']!=""){
// $telefone = $notafiscal['cliente']['fone'];
// }
// }
$telefones = [];
if(isset($notafiscal['cliente']['celular'])){
if($notafiscal['cliente']['celular']!=""){
$telefone = $notafiscal['cliente']['celular'];
$telefone = '55'.$telefone;
$telefones[] = preg_replace('/\D/', '', $telefone);
}
}
if(isset($notafiscal['cliente']['celular'])){
if($notafiscal['cliente']['celular']!=""){
$telefone = $notafiscal['cliente']['celular'];
$telefone = '55'.$telefone;
$telefones[] = preg_replace('/\D/', '', $telefone);
}
}
$dados['telefone'] = implode('|', $telefones);
if(isset($notafiscal['cliente']['nome'])){
$dados['contato'] = $notafiscal['cliente']['nome'];
}
if(!empty($notafiscal['cliente'])){
$dados['endereco'] = $notafiscal['cliente']['endereco'] . ', ' .
$notafiscal['cliente']['numero'] . ', ' .
$notafiscal['cliente']['complemento'] . ', ' .
$notafiscal['cliente']['bairro'] . ', ' .
$notafiscal['cliente']['cidade'] . '/' .
$notafiscal['cliente']['uf'] . ', ' .
$notafiscal['cliente']['cep'] . ', ';
}
$dados['vendedor'] = $notafiscal['vendedor'];
$dados['cnpj'] = '';
if(isset($notafiscal['cliente']['cnpj'])){
$dados['cnpj'] = $notafiscal['cliente']['cnpj'];
}
return $dados;
// return [
// 'quantidade' => $volume,
// 'emissao' => $data[2] . '/' . $data[1] . '/' . $data[0],
// 'pedido' => $numero,
// 'cliente' => $notafiscal['cliente']['nome'],
// 'telefone' => $telefone,
// 'tipo' => 'nf',
// 'transportadora' => $trasportadora
// ];
}
}
}
}
return false;
}
private function isAdmin() {
return ($this->getUser()->getEmail()=='bruno@moveispollo.com.br');
}
private function getDadosCliente($pedido, $client){
if(empty($pedido)) {
return '';
}
$dados = [
'telefone' =>'',
'endereco' => '',
'produtos' => []
];
$numero = '';
$lojas = [
['nome' => 'polo', 'api' => SincronizacaoController::KEY_API_POLLO]
];
foreach ($lojas as $loja) {
$response = $client->request(
'GET',
SincronizacaoController::URL_API_BLING . '/pedido/'.$pedido.'/json/',
[
'query' => [
'apikey' => $loja['api']
]
]
);
$statusCode = $response->getStatusCode();
if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
$content = $response->toArray();
if(isset($content['retorno'])){
if(isset($content['retorno']['pedidos'])){
if(count($content['retorno']['pedidos']) > 0) {
if(isset($content['retorno']['pedidos'][0])){
if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'])){
$dados['endereco'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['endereco'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['numero'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['complemento'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['bairro'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['cidade'] . '/' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['uf'] . ', ' .
$content['retorno']['pedidos'][0]['pedido']['cliente']['cep'] . ', ';
}
if(!empty($content['retorno']['pedidos'][0]['pedido']['itens'])){
if(count($content['retorno']['pedidos'][0]['pedido']['itens'])>0){
$produtos = '';
$totalProdutos = 0;
foreach ($content['retorno']['pedidos'][0]['pedido']['itens'] as $item){
$quantidade = $item['item']['quantidade'];
$valorTotal = $item['item']['valorunidade'] * $quantidade;
$produtos .= "*Qtd:* " . round($item['item']['quantidade']) . " - " . $item['item']['descricao'] . " - R$ " .
number_format($valorTotal, 2, ',', '.') . "\n";
$totalProdutos+=$valorTotal;
}
$valorComDesconto = $content['retorno']['pedidos'][0]['pedido']['totalvenda'];
$produtosStr = "\n*Total Nota:* R$ " . number_format($totalProdutos, 2, ',', '.');
$produtosStr .= "\n*Total c/ desconto:* R$ " . number_format($valorComDesconto, 2, ',', '.');
$dados['produtos'] = $produtos . $produtosStr;
}
}
$telefones = [];
if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['celular'])){
if($content['retorno']['pedidos'][0]['pedido']['cliente']['celular']!=""){
$telefone = $content['retorno']['pedidos'][0]['pedido']['cliente']['celular'];
$telefone = '55'.$telefone;
$telefones[] = preg_replace('/\D/', '', $telefone);
}
}
if(isset($content['retorno']['pedidos'][0]['pedido']['cliente']['fone'])){
if($content['retorno']['pedidos'][0]['pedido']['cliente']['fone']!=""){
$telefone = $content['retorno']['pedidos'][0]['pedido']['cliente']['fone'];
$telefone = '55'.$telefone;
$telefones[] = preg_replace('/\D/', '', $telefone);
}
}
$dados['telefone'] = implode('|', $telefones);
// if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['fone'])){
// $dados['telefone'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['fone'];
// }
// if(!empty($content['retorno']['pedidos'][0]['pedido']['cliente']['celular'])){
// $dados['telefone'] = $content['retorno']['pedidos'][0]['pedido']['cliente']['celular'];
// }
$dados['vendedor'] = $content['retorno']['pedidos'][0]['vendedor'];
return $dados;
break;
}
}
}
}
}
}
return $dados;
}
private function todosPedidosPorStatus($pedidoFiltrado='', $fieldPassed='pedido', $busca=false, $tipo='') {
$pedidosDatabaixado = [];
if($busca){
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilter($fieldPassed, $pedidoFiltrado, $tipo);
foreach ($pedidos as $pedido) {
$pedidosDatabaixado[] = $this->makeProdutoData($pedido);
}
$mensagensChat = $this->getAllMensagensChat();
$temMensagemNaoLida = false;
foreach ($mensagensChat as $mensagemChat) {
if(!$mensagemChat['isLida']){
$temMensagemNaoLida = true;
break;
}
}
return [
'pendentes' => [],
'aceitos' => [],
'entregues' => [],
'transito' => [],
'pendentes_admin' => [],
'baixados' => $pedidosDatabaixado,
'recebidos' => [],
'cotacao' => [],
'aguardando_pagamento' => [],
'naoLidos' => $this->getPedidosNaoLidos(),
'mensagensChat' => $this->getAllMensagensChat(),
'temMensagemNaoLida' => $temMensagemNaoLida
];
}
$pedidosDataPendentes = $this->getPedidos('pendente');
$pedidosDataAceitos = $this->getPedidos('aceito');
$pedidosDataEntregues = $this->getPedidos('entregue');
$pedidosDataTransito = $this->getPedidos('transito');
$pedidosDataPendenteAdmin = $this->getPedidos('pendente_admin');
$pedidosDatabaixado = $this->getPedidos('baixado', $busca);
$pedidosDataRecebido = $this->getPedidos('recebido');
$pedidosDataCotacao = $this->getPedidos('cotacao');
$pedidosDataAguardandoPagamento = $this->getPedidos('aguardando_pagamento');
if($pedidoFiltrado!=''){
$jaExisteNaLista = false;
$field = ($fieldPassed=='sku') ? 'pedido' : 'nota';
foreach ($pedidosDataPendentes as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataAceitos as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataEntregues as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataTransito as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataPendenteAdmin as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDatabaixado as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataRecebido as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataCotacao as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
foreach ($pedidosDataAguardandoPagamento as $pedido) {
if($pedido['pedido']==$pedidoFiltrado || $pedido['nota']==$pedidoFiltrado || $pedido['pedido']==$pedidoFiltrado.'-Assistência' || $pedido['nota']==$pedidoFiltrado.'-Assistência') {
$jaExisteNaLista = true;
}
}
if(!$jaExisteNaLista) {
$pedidos = $this->getDoctrine()->getRepository(EntregaPedido::class)->pedidosFilter($fieldPassed, $pedidoFiltrado, $tipo);
foreach ($pedidos as $pedido) {
$pedidosDatabaixado[] = $this->makeProdutoData($pedido);
}
}
}
$mensagensChat = $this->getAllMensagensChat();
$temMensagemNaoLida = false;
foreach ($mensagensChat as $mensagemChat) {
if(!$mensagemChat['isLida']){
$temMensagemNaoLida = true;
break;
}
}
return [
'pendentes' => $pedidosDataPendentes,
'aceitos' => $pedidosDataAceitos,
'entregues' => $pedidosDataEntregues,
'transito' => $pedidosDataTransito,
'pendentes_admin' => $pedidosDataPendenteAdmin,
'baixados' => $pedidosDatabaixado,
'recebidos' => $pedidosDataRecebido,
'cotacao' => $pedidosDataCotacao,
'aguardando_pagamento' => $pedidosDataAguardandoPagamento,
'naoLidos' => $this->getPedidosNaoLidos(),
'mensagensChat' => $this->getAllMensagensChat(),
'temMensagemNaoLida' => $temMensagemNaoLida
];
}
private function getProduto($apiKeyStore, $codigoProduto, $client, $xml=false) {
$format = 'json';
if($xml){
$format = 'xml';
}
$response = $client->request(
'GET',
SincronizacaoController::URL_API_BLING . '/produto/'.$codigoProduto.'/'.$format,
[
'query' => [
'apikey' => $apiKeyStore,
'estoque' => 'S',
'imagem' => 'S',
'situacao' => 'A'
]
]
);
$statusCode = $response->getStatusCode();
if ($statusCode == SincronizacaoController::HTTP_STATUS_CODE_OK) {
if($xml){
return $response->getContent();
}
$content = $response->toArray();
return $content;
} else {
return [];
}
return [];
}
}