<?php
namespace App\Controller\App;
use App\Application\Sonata\UserBundle\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use App\Entity\AcessoCliente;
use App\Entity\Cliente;
use App\Entity\RelatorioTecnico;
use App\Entity\OrdemDeServico;
use App\Entity\Concretagem;
use App\Entity\RelatorioIndividualMassa;
use App\Entity\RelatorioTecnicoMassa;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Knp\Snappy\Pdf;
class AcessoClienteController extends AbstractController
{
private $snappyPDF;
public function __construct(Pdf $snappyPDF)
{
$this->snappyPDF = $snappyPDF;
}
/**
* @Route("/acesso-cliente", name="acesso_cliente", methods={"GET"})
*/
public function acessoCliente(Request $request)
{
return $this->render('acessoCliente/index.html.twig');
}
##### API PUBLICA CLIENTE #####\
/**
* @Route("/acesso-cliente/relatorio-pdf-os/{id}/{token}", name="acesso_cliente_relatorio_pdf_os", methods={"GET"})
*/
public function acessoRelatorioClienteOs(Request $request, $id, $token)
{
$acessoCliente = $this->userIsValid($token);
if(!$acessoCliente instanceof AcessoCliente){
return new JsonResponse(['message'=>'Usuário não autenticado'], Response::HTTP_FORBIDDEN);
}
$relatorio = $this->getDoctrine()->getRepository(RelatorioTecnico::class)->find($id);
if(!$relatorio instanceof RelatorioTecnico){
return new JsonResponse(['message'=>sprintf('Relatório não localizado com o id: %s', $id)], Response::HTTP_FORBIDDEN);
}
// Esse Relatório é desse cliente
if($relatorio->getOrdemServico()->getProposta()->getCliente()->getId() != $acessoCliente->getCliente()->getId()){
return new JsonResponse(['message'=>sprintf('Relatório não localizado com o id para este cliente: %s', $id)], Response::HTTP_FORBIDDEN);
}
$basedir = $this->getParameter('kernel.root_dir') . '/../public' . $request->getBasePath();
if($relatorio->getRelatorioAnexo()){
$file=$basedir . '/' . $relatorio->getRelatorioAnexo();
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="the.pdf"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($file));
@readfile($file);
} else {
#### MOCKUP RELATORIO
$imagensCadastradasNaOsParaCada = [];
/** @var ImagemRelatorio $imagem */
foreach ($relatorio->getImagensrelatorio() as $imagem) {
$imagensCadastradasNaOsParaCada[] = [
'resultado_id'=> $imagem->getId(),
'resultado_figura' => $basedir . '/uploads/' . $imagem->getLogo(),
'resultado_titulo' => $imagem->getTitulo(),
'servico_id' => $imagem->getId(),
'servico_titulo' => $imagem->getTitulo()
];
}
### MOCKUP RELATORIO
$params = [
'basedir' => $basedir,
'relatorio' => $relatorio,
'resultados' => $imagensCadastradasNaOsParaCada,
'total_paginas_resultados' => count($imagensCadastradasNaOsParaCada)+4,
'figura_resumo' => $relatorio->getLogoOriginal(),
];
$headerHtml = $this->renderView(
'RelatoriosTecnicos/header-relatorio-tecnico-pdf.html.twig', $params
);
$footerHtml = $this->renderView(
'RelatoriosTecnicos/footer-relatorio-tecnico-pdf.html.twig', $params
);
$html = $this->renderView('RelatoriosTecnicos/relatorio-tecnico-pdf.html.twig', $params);
return new PdfResponse(
$this->snappyPDF->getOutputFromHtml($html, [
'orientation' => 'Portrait',
'encoding' => 'utf-8',
//'header-html' => $headerHtml,
'header-spacing' => 0,
//'footer-right' => 'Pagina [page]/[toPage]',
'footer-html' => $footerHtml,
'footer-font-size' => '9',
'footer-spacing' => 4,
'margin-top' => '12mm', // Para aparecer o header
'margin-bottom' => '30mm', // Para aparecer o footer
]),
'Relatorio Tecnico-'.$relatorio->getId().'.pdf',
'application/pdf',
'inline'
);
}
exit();
}
// Base64 URL encode
private function base64UrlEncode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}
private function acessFileGoogleDrive($relatoriosMassaIndividual) {
$filderGoogleDriveID = '1iYGbxxixMt9_QWfbSFI-FDoN8G0FP8PP';
$nomeArquivo = basename($relatoriosMassaIndividual->getPathFile()); // garante só o nome
$service_account_key = '{
"type": "service_account",
"project_id": "ltec-arquivos",
"private_key_id": "bcec8a138b5a1731bc6a487b2f64a747c1b5246f",
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTBQKc11cVrUe5\nUaeKfHf3wlqbOQSJxEIOblZRaHYB+h+QdQPeZR442fx6Mfn4R6O0MJ82wnqtqvCr\nyI1DE7MA9Tv5XCpb9szUUiiqXPXkGu+4fKuogBWr5wDxX3+uJSI5x/wSq10aN1Rg\nUikYFkCtRYCO/JwtrC4JqpnhlqQB1Gx42Y1iTFqlVEGDMiafTO+ZZYaW8000jeED\nFWcQmyRMZfu++ywHHUUIbHwAxXg8cuaNEqLcXbRILJhsNOw20W7qJfGw0m8FiJfl\n0IOfDl9b6SmMCVh0cRAJndmPMLMQaZlK6NVKaicONYDG3RKSY4+gDtybUSzFkhWJ\n++zk0jBBAgMBAAECggEAAgGOPtIgZdMSuLhgwx6+K1MLVfVh9rhHF3fRdTRp8c52\nKkwydJEoJ6nvzEIM0WK23OFR9tcSAfckaA+pP8pPxbpS6mzjxhP4yQfi9qokj8t/\nTGLlG7w9r3YMOP7u2NM4Y5XzPlT4xQAOxm6wkVvSX5rkbW8MeYIRMcASb/XUgJLe\naBRTL3dd8mcVgDETNMLZobWqqH8SwDy+54IjSPLP2XI45p08VPUi1lwpEa3Z+97n\nXu4Ye1f+Cya1tLfDfEpw73ZlrQZ2PZRtUcYP4SrJBw1Q/ixZFcDTdZLcHgoEId/v\nJyalUbB/ofujXFVtFP1t9NkvhaNVvn4rPpRSH3lWwQKBgQDLpp1r15MhoksJZCG+\n4XZeqsGTChtFwNHfXEeehd8D63pHrlmsUUJWrJEWORhRKzbDpLBVlMoQEZFuwyyk\n/LDOda9IXsqDHSPD0a+7cMfEmJnE28dbyNh4H+XxE2bURLRwLT34hvxzAj6VW3Ob\n0zXCRlPA9NSy+Vp/q4wWH+v5EQKBgQC4z7w78FXpIs2ztmjSSDw5UL8vZ/3RZpEY\nsgcrNcFoqQqFhVHb1cirFe90/5gQmlIJ6AknJqmlLJXoVs8bxP21TxTJsQjGm9bd\nnH/six/UkK814sJOg/kBuD6wMCyV5hjrQacBmMEhn4hR14qNdT7Zy6CFjOfcrtPS\noYN2Wo9EMQKBgQCiK3/YTMahVfei9tXYhvoX0KptSPMGzNFTqMxvc/Nvz6iERFas\nXdkR5EF1DOpMWLk3eoHg5KczvImvRkTa7U5uWlDGtJVXa3D7kpL6FIlACLUKimlq\nsbmPjvcwzl5oUn3Nhnl+2x9VBkiH71dUkxCQMCip0009aEuktxrK04i5wQKBgGND\nMFcBPyN5DgL4dlR7d91RAV70+978t/ILrM4IkVklcgFFGjJ5IM7DeVnd7k78lBO+\nDSx6F6QfzmR8O8EujRZU41VxQMVr7nwZEpx6HR6Ol4zZvoNtXtENpJ39QfVBISE6\nofi5kwH8LbvHiSNxVdClDhKtG9vsCtmW5oUrHsgBAoGAOMx5OQ/uh66j1NoAN9Mp\nFyFOnns6GJABY9YxfMmHrW8kxkrrWzX/Hi7B9c8UDNL6GgrwIAWRlaVXrEzQYix2\na9dvoCJq0YUfM0i50oWZZ+9R7A16zIqRksmBPtB7+IvNZ0v0apAjfZ8nijlea92X\nfrxazWURBLkmCEtLv5Bml/I=\n-----END PRIVATE KEY-----\n",
"client_email": "ltec-acesso-arquivos@ltec-arquivos.iam.gserviceaccount.com",
"client_id": "113733670713829067657",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/ltec-acesso-arquivos%40ltec-arquivos.iam.gserviceaccount.com",
"universe_domain": "googleapis.com"
}';
// 2) Obter access_token da service account (seu código atual aqui)
$sa = json_decode($service_account_key, true);
$header = [
"alg" => "RS256",
"typ" => "JWT"
];
$now = time();
$payload = [
"iss" => $sa["client_email"],
"scope" => "https://www.googleapis.com/auth/drive.readonly",
"aud" => $sa["token_uri"],
"exp" => $now + 3600,
"iat" => $now
];
$jwtHeader = $this->base64UrlEncode(json_encode($header));
$jwtPayload = $this->base64UrlEncode(json_encode($payload));
$jwtUnsigned = $jwtHeader . "." . $jwtPayload;
openssl_sign($jwtUnsigned, $signature, $sa["private_key"], "sha256WithRSAEncryption");
$jwtSignature = $this->base64UrlEncode($signature);
$jwt = $jwtUnsigned . "." . $jwtSignature;
// 3) Troca JWT por access_token
$urlToken = $sa["token_uri"];
$ch = curl_init($urlToken);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
"grant_type" => "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion" => $jwt
]));
$responseToken = curl_exec($ch);
curl_close($ch);
$token = json_decode($responseToken, true);
if (!isset($token["access_token"])) {
die("Erro ao obter access_token:\n" . $responseToken);
}
$accessToken = $token['access_token'];
// 5) Buscar o arquivo pelo nome dentro da pasta imported
// Monta a query: name='xxx.pdf' and 'PASTA_ID' in parents
// IMPORTANTE: escapar aspas simples
$nomeEscapado = str_replace("'", "\\'", $nomeArquivo);
$q = "name='{$nomeEscapado}' and '{$filderGoogleDriveID}' in parents";
$qUrl = urlencode($q);
$urlBusca = "https://www.googleapis.com/drive/v3/files"
. "?q={$qUrl}"
. "&fields=files(id,name,mimeType)";
$ch = curl_init($urlBusca);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $accessToken"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$responseBusca = curl_exec($ch);
curl_close($ch);
$resultBusca = json_decode($responseBusca, true);
// DEBUG opcional:
// echo "<pre>"; var_dump($resultBusca); echo "</pre>"; exit;
// 6) Verifica se achou algum arquivo
if (!isset($resultBusca["files"][0])) {
http_response_code(404);
die("Arquivo '{$nomeArquivo}' não encontrado na pasta imported.");
}
$fileId = $resultBusca["files"][0]["id"];
$mimeType = $resultBusca["files"][0]["mimeType"] ?? 'application/pdf';
// 7) Baixar o arquivo pelo ID
$urlDownload = "https://www.googleapis.com/drive/v3/files/{$fileId}?alt=media";
$ch = curl_init($urlDownload);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Authorization: Bearer $accessToken"
]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode !== 200) {
echo "Erro ao baixar arquivo. HTTP {$httpCode}<br><pre>";
var_dump($data);
echo "</pre>";
exit;
}
// 8) Devolver o PDF
header("Content-Type: $mimeType");
header("Content-Disposition: inline; filename=\"{$nomeArquivo}\"");
echo $data;
exit;
}
/**
* @Route("/acesso-cliente/relatorio-individual/{id}/{token}", name="acesso_cliente_relatorio_individual_pdf", methods={"GET"})
*/
public function acessoRelatorioClienteIndividual(Request $request, $id, $token)
{
//exit('Indisponível no momento. Este sistema está em manutenção.');
$dirSave = "/www/wwwroot/gestor.ltec.eng.br/public/uploads/relatorios_massa/imported";
$relatoriosMassaIndividual = $this->getDoctrine()->getRepository(RelatorioIndividualMassa::class)->find($id);
if(!$relatoriosMassaIndividual instanceof RelatorioIndividualMassa){
exit('Arquivo não localizado');
}
//$titulo = $this->criarSlug($relatoriosMassaIndividual->getTitulo());
//$titulo = str_ireplace('PDF', '', $titulo);
$nomeArquivoLocal = $dirSave . '/' . $relatoriosMassaIndividual->getPathFile();
// Verifique se o arquivo existe
if (file_exists($nomeArquivoLocal)) {
// Defina os cabeçalhos apropriados para PDF
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . $relatoriosMassaIndividual->getTitulo() . '.pdf"');
header('Content-Length: ' . filesize($nomeArquivoLocal));
// Abra o arquivo em modo binário para leitura
$arquivo = fopen($nomeArquivoLocal, 'rb');
// Envie o conteúdo binário do arquivo para o navegador
while (!feof($arquivo)) {
echo fread($arquivo, 8192); // Leia e envie em pedaços
}
// Feche o arquivo
fclose($arquivo);
} else {
$this->acessFileGoogleDrive($relatoriosMassaIndividual);
}
exit($titulo);
}
function criarSlug($nomeArquivo) {
// Remove a acentuação
$nomeArquivo = strtr($nomeArquivo, 'àáâãäåæçèéêëìíîïðñòóôõöøùúûüýÿ', 'aaaaaaaceeeeiiiinoooooouuuuyy');
// Converte para maiúsculas
$nomeArquivo = strtoupper($nomeArquivo);
// Substitui espaços em branco por hífens
$nomeArquivo = preg_replace('/\s+/', '-', $nomeArquivo);
// Remove caracteres especiais
$nomeArquivo = preg_replace('/[^A-Za-z0-9\-]/', '', $nomeArquivo);
return $nomeArquivo;
}
/**
* @Route("/acesso-cliente/relatorio-pdf/{id}/{token}", name="acesso_cliente_relatorio_pdf", methods={"GET"})
*/
public function acessoRelatorioCliente(Request $request, $id, $token)
{
$acessoCliente = $this->userIsValid($token);
if(!$acessoCliente instanceof AcessoCliente){
return new JsonResponse(['message'=>'Usuário não autenticado'], Response::HTTP_FORBIDDEN);
}
// Tenho o cliente
// Preciso pegar todas as os do cliente
$ossByClienteEntity = $this->getDoctrine()->getRepository(OrdemDeServico::class)->findByCliente($acessoCliente->getCliente());
$relatorios = [];
foreach ($ossByClienteEntity as $os) {
// Pegar os moldes dentro do intervalo liberado
// (['os'=>$os],['ordemRelatorio'=>'asc','createdAt'=>'desc']
$moldesDaOsPorIntervalo = $this->getDoctrine()->getRepository(Concretagem::class)->findByOsEIntervalo(
$os,
$acessoCliente->getDataInicial(),
$acessoCliente->getDataFinal()
);
foreach ($moldesDaOsPorIntervalo as $molde) {
$repo = $this->getDoctrine()->getRepository(Concretagem::class);
$id = $molde->getId();
$molde = $repo->find($id);
if(!$molde instanceof Concretagem) {
throw new NotFoundHttpException(sprintf('Molde não localizado com o id: %s', $id));
}
// Criar um array de cps agrupados por prova e contraprova
$linhasCP = [];
$diasTestados = [];
foreach($molde->getMoldes() as $moldeItem){
// Busca se já tem alguem com o mesmo dia
$key = 'dias_'.$moldeItem->getDiasRompimento();
if(array_key_exists($key,$linhasCP)){
$linhasCP[$key][] = $moldeItem;
} else {
$diasTestados[] = $moldeItem->getDiasRompimento();
$linhasCP[$key] = [$moldeItem];
}
}
asort($diasTestados);
$maiorValorCP = 0;
foreach($molde->getMoldes() as $moldeItem){
if($moldeItem->getValorRompimento()>$maiorValorCP){
$maiorValorCP = $moldeItem->getValorRompimento();
}
}
$valores = [];
foreach($diasTestados as $diaTestado){
$valores[$diaTestado] = 0;
}
foreach($linhasCP as $linha){
$valores[$linha[0]->getDiasRompimento()] = $linha[0]->getValorRompimento();
}
$valores = implode($valores,',');
$diasTestados = implode($diasTestados,'|');
$maiorValorCPCalculado = 0;
$maiorValorCPCalculado = (($maiorValorCP*1000)/78.54)/10;
$params = [
'molde' => $molde,
'moldes' => $linhasCP,
'maiorValor' => ceil($maiorValorCP),
'maiorValorCalculado' => $maiorValorCPCalculado,
'valores' => $valores,
'diasTestados' => $diasTestados
];
$relatorios[] = $params;
}
}
$html = $this->renderView('Os/relatorios_cps.html.twig', ['relatorios'=>$relatorios]);
//return $this->render('Os/relatorio_cp.html.twig',$params);
return new PdfResponse(
$this->snappyPDF->getOutputFromHtml($html, [
'orientation' => 'Portrait',
'encoding' => 'utf-8',
//'header-html' => $headerHtml,
'header-spacing' => 0,
//'footer-right' => 'Pagina [page]/[toPage]',
//'footer-html' => $footerHtml,
//'footer-font-size' => '9',
//'footer-spacing' => 4,
'margin-top' => '10mm', // Para aparecer o header
'margin-bottom' => '5mm', // Para aparecer o footer
]),
'Relatorio-cp-os-'.$id.'.pdf',
'application/pdf',
'inline'
);
}
/**
* @Route("/acesso-cliente/login", name="acesso_cliente_login", methods={"POST"})
*/
public function acessoClienteLogin(Request $request)
{
$data = json_decode($request->getContent(), false);
$acessoCliente = $this->getDoctrine()->getRepository(AcessoCliente::class)->findOneBy(['email'=>$data->username,'senha'=>$data->senha]);
if(!$acessoCliente instanceof AcessoCliente) {
return new JsonResponse([], 400);
}
// Refresh token
$acessoCliente->setToken($this->generateToken(40));
$this->getDoctrine()->getManager()->flush();
return new JsonResponse([
'token'=>$acessoCliente->getToken()
], Response::HTTP_OK);
}
/**
* @Route("/acesso-cliente/relatorios-disponiveis", name="acesso_cliente_relatorios", methods={"POST"})
*/
public function getRelatoriosDisponiveis(Request $request)
{
$data = json_decode($request->getContent(), false);
$user = $this->userIsValid($data->token);
if(!$user instanceof AcessoCliente){
return new JsonResponse(['message'=>'Usuário não autenticado'], Response::HTTP_FORBIDDEN);
}
$relatoriosCp = [];
$relatoriosEntity = $this->getDoctrine()->getRepository(AcessoCliente::class)->findBy([
'email'=>$user->getEmail(),
'token'=>$user->getToken(),
]);
$osPermitidas = [];
if(count($relatoriosEntity)){
if($relatoriosEntity[0]->getOsAcessos() != null){
if(count($relatoriosEntity[0]->getOsAcessos())>0){
foreach($relatoriosEntity[0]->getOsAcessos() as $oss){
$osPermitidas[] = $oss->getId();
}
}
}
}
foreach ($relatoriosEntity as $relatorio) {
$dataInicial = $relatorio->getDataInicial();
$dataFinal = $relatorio->getDataFinal();
if ($dataInicial instanceof \DateTimeInterface) {
// Se dataFinal for null, adiciona 1 mês à dataInicial
if (!$dataFinal) {
$dataFinal = (clone $dataInicial)->add(new \DateInterval('P1M'));
}
$relatoriosCp[] = [
'id' => $relatorio->getId(),
'finalidade' => 'Finalidade',
'dataInicial' => $dataInicial->format('d/m/Y'),
'dataFinal' => $dataFinal->format('d/m/Y'),
'tipo' => 'cp'
];
}
}
// Get relatórios plataforma
$relatoriosData = [];
if(count($relatoriosEntity)){
if($relatoriosEntity[0]->getCliente() instanceof Cliente){
$relatorios = $this->getDoctrine()->getRepository(RelatorioTecnico::class)->findPorCliente($relatoriosEntity[0]->getCliente());
foreach ($relatorios as $relatorio){
if(!in_array($relatorio->getOrdemServico()->getId(), $osPermitidas) && count($osPermitidas)>0){
continue;
}
$relatoriosData[] = [
'id'=>$relatorio->getId(),
'data'=>$relatorio->getCreatedAt()->format('d/m/Y'),
'os'=>$relatorio->getOrdemServico()->getProposta()->getNumeroFormatado(),
'relatorioAnexo' => $relatorio->getRelatorioAnexo(),
'isLiberadoParaCliente' => $relatorio->getIsLiberadoParaCliente(),
'tipo' => 'os'
];
}
}
}
$relatoriosAgregados = [];
if(count($relatoriosEntity)){
if($relatoriosEntity[0]->getCliente() instanceof Cliente){
$relatorios = $this->getDoctrine()->getRepository(RelatorioTecnicoMassa::class)->findPorClienteAgregados($relatoriosEntity[0]->getCliente());
foreach ($relatorios as $relatorio){
if(!in_array($relatorio->getOs()->getId(), $osPermitidas) && count($osPermitidas)>0){
continue;
}
$relatoriosInternos = [];
$relatoriosMassaIndividual = $this->getDoctrine()->getRepository(RelatorioIndividualMassa::class)->findBy(['relatorioTecnicoMassa'=>$relatorio], ['numero'=>'ASC', 'titulo'=>'ASC']);
foreach ($relatoriosMassaIndividual as $relatorioMassaIndividual) {
$relatoriosInternos[] = [
'id' => $relatorioMassaIndividual->getId(),
'titulo'=>str_ireplace('.pdf', '', $relatorioMassaIndividual->getTitulo()),
'data'=>$relatorioMassaIndividual->getData()->format('d/m/Y'),
'numero'=>str_pad($relatorioMassaIndividual->getNumero(), 3, "0", STR_PAD_LEFT),
'pecaConcretada'=>$relatorioMassaIndividual->getPecaConcretada(),
'file'=>$relatorioMassaIndividual->getPathFile(),
];
}
$relatoriosAgregados[] = [
'id'=>$relatorio->getId(),
'data'=>$relatorio->getCreatedAt()->format('d/m/Y'),
'os'=>$relatorio->getOs()->getProposta()->getNumeroFormatado(),
'relatorioAnexo' => '',
'isLiberadoParaCliente' => true,
'tipo' => 'agregado',
'sub' => $relatoriosInternos
];
}
}
}
$showDocumentsDownload = false;
if(count($relatoriosEntity)>0) {
$showDocumentsDownload = ($relatoriosEntity[0]->getCliente()->getFranquia()->getId() == 1) ? true : false;
}
$relatoriosResult = ['cp'=>$relatoriosCp, 'plataforma'=>$relatoriosData, 'agregados' => $relatoriosAgregados,
'showDocumentsDownload'=>$showDocumentsDownload, 'cnpj'=>''];
return new JsonResponse($relatoriosResult, Response::HTTP_OK);
}
/**
* @Route("/acesso-cliente/muda-senha", name="muda_senha_acesso_cliente", methods={"PUT"})
*/
public function mudaSenhaPeloCliente(Request $request)
{
return new JsonResponse([], Response::HTTP_OK);
}
#### TOOLS ####
private function generateToken($length = 20)
{
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$charactersLength = strlen($characters);
$randomString = '';
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
private function userIsValid($token) {
$acessoCliente = $this->getDoctrine()->getRepository(AcessoCliente::class)->findOneBy(['token'=>$token]);
if(!$acessoCliente instanceof AcessoCliente) {
return false;
}
return $acessoCliente;
}
}