diff --git a/BD/wegia001.sql b/BD/wegia001.sql index 8669341b..fce8ccee 100755 --- a/BD/wegia001.sql +++ b/BD/wegia001.sql @@ -819,6 +819,33 @@ CREATE TABLE `wegia`.`contribuicao_conjuntoRegras` ( CONSTRAINT `unico_meioPagamento_regra` UNIQUE (`id_meioPagamento`, `id_regra`) ) ENGINE = InnoDB; +-- ----------------------------------------------------- +-- Table `wegia`.`contribuicao_log` +-- ----------------------------------------------------- +CREATE TABLE IF NOT EXISTS wegia.contribuicao_log ( +id INT NOT NULL AUTO_INCREMENT, +id_socio INT(11) NOT NULL, +id_gateway INT(11) NOT NULL, +id_meio_pagamento INT(11) NOT NULL, +codigo VARCHAR(255) NOT NULL UNIQUE, +valor DECIMAL(10,2) NOT NULL, +data_geracao DATE NOT NULL, +data_vencimento DATE NOT NULL, +data_pagamento DATE, +status_pagamento BOOLEAN NOT NULL, +PRIMARY KEY (id), +CONSTRAINT FK_id_socios +FOREIGN KEY (id_socio) +REFERENCES wegia.socio (id_socio), +CONSTRAINT FK_id_gateways +FOREIGN KEY (id_gateway) +REFERENCES wegia.contribuicao_gatewayPagamento (id), +CONSTRAINT FK_id_meio_pagamentos +FOREIGN KEY (id_meio_pagamento) +REFERENCES wegia.contribuicao_meioPagamento (id) +) +ENGINE = InnoDB; + -- ----------------------------------------------------- -- Table `wegia`.`socio_status` diff --git a/html/apoio/controller/ContribuicaoLogController.php b/html/apoio/controller/ContribuicaoLogController.php index f29a0462..15692e67 100755 --- a/html/apoio/controller/ContribuicaoLogController.php +++ b/html/apoio/controller/ContribuicaoLogController.php @@ -52,6 +52,7 @@ public function criarBoleto() //Talvez seja melhor separar em: criarBoleto, cria $gatewayPagamentoDao = new GatewayPagamentoDAO(); $gatewayPagamentoArray = $gatewayPagamentoDao->buscarPorId($meioPagamento->getGatewayId()); $gatewayPagamento = new GatewayPagamento($gatewayPagamentoArray['plataforma'], $gatewayPagamentoArray['endPoint'], $gatewayPagamentoArray['token'], $gatewayPagamentoArray['status']); + $gatewayPagamento->setId($meioPagamento->getGatewayId()); //Requisição dinâmica e instanciação da classe com base no nome do gateway de pagamento $requisicaoServico = '../service/' . $gatewayPagamento->getNome() . $formaPagamento . 'Service' . '.php'; @@ -98,23 +99,28 @@ public function criarBoleto() //Talvez seja melhor separar em: criarBoleto, cria ->setCodigo($contribuicaoLog->gerarCodigo()) ->setDataGeracao($dataGeracao) ->setDataVencimento($dataVencimento) - ->setSocio($socio); + ->setSocio($socio) + ->setGatewayPagamento($gatewayPagamento) + ->setMeioPagamento($meioPagamento); try { /*Controle de transação para que o log só seja registrado caso o serviço de pagamento tenha sido executado*/ $this->pdo->beginTransaction(); $contribuicaoLogDao = new ContribuicaoLogDAO($this->pdo); - $contribuicaoLogDao->criar($contribuicaoLog); + $contribuicaoLog = $contribuicaoLogDao->criar($contribuicaoLog); //Registrar na tabela de socio_log $mensagem = "Boleto gerado recentemente"; $socioDao->registrarLog($contribuicaoLog->getSocio(), $mensagem); + $codigoApi = $servicoPagamento->gerarBoleto($contribuicaoLog); + //Chamada do método de serviço de pagamento requisitado - if (!$servicoPagamento->gerarBoleto($contribuicaoLog)) { + if (!$codigoApi) { $this->pdo->rollBack(); } else { + $contribuicaoLogDao->alterarCodigoPorId($codigoApi, $contribuicaoLog->getId()); $this->pdo->commit(); } } catch (PDOException $e) { @@ -157,6 +163,7 @@ public function criarCarne() $gatewayPagamentoDao = new GatewayPagamentoDAO(); $gatewayPagamentoArray = $gatewayPagamentoDao->buscarPorId($meioPagamento->getGatewayId()); $gatewayPagamento = new GatewayPagamento($gatewayPagamentoArray['plataforma'], $gatewayPagamentoArray['endPoint'], $gatewayPagamentoArray['token'], $gatewayPagamentoArray['status']); + $gatewayPagamento->setId($meioPagamento->getGatewayId()); //Requisição dinâmica e instanciação da classe com base no nome do gateway de pagamento $requisicaoServico = '../service/' . $gatewayPagamento->getNome() . $formaPagamento . 'Service' . '.php'; @@ -171,121 +178,120 @@ public function criarCarne() $classeService = $gatewayPagamento->getNome() . $formaPagamento . 'Service'; if (!class_exists($classeService)) { - echo json_encode(['erro' => 'Classe não encontrada']); + echo json_encode(['erro' => 'Classe não encontrada']); exit(); } $servicoPagamento = new $classeService; - } catch (PDOException $e) { - //implementar tratamento de erro - echo json_encode(['erro' => $e->getMessage()]); - exit(); - } - //Criar coleção de contribuições - $contribuicaoLogCollection = new ContribuicaoLogCollection(); + /*Controle de transação para que o log só seja registrado + caso o serviço de pagamento tenha sido executado*/ + $this->pdo->beginTransaction(); - if (!$qtdParcelas || $qtdParcelas < 2) { - //implementar mensagem de erro - exit('O mínimo de parcelas deve ser 2'); - } + $contribuicaoLogDao = new ContribuicaoLogDAO($this->pdo); - // Pegar a data atual - $dataAtual = new DateTime(); + //Criar coleção de contribuições + $contribuicaoLogCollection = new ContribuicaoLogCollection(); - if (isset($_POST['tipoGeracao']) && !empty($_POST['tipoGeracao'])) { - //verificar autenticação do funcionário - require_once '../../permissao/permissao.php'; + if (!$qtdParcelas || $qtdParcelas < 2) { + //implementar mensagem de erro + exit('O mínimo de parcelas deve ser 2'); + } - session_start(); - permissao($_SESSION['id_pessoa'], 4); + // Pegar a data atual + $dataAtual = new DateTime(); - //escolher qual ação tomar - $tipoGeracao = $_POST['tipoGeracao']; - - //chamar funções - require_once '../helper/Util.php'; - - $datasVencimento; - - $diaVencimento = ($_POST['dia']); - - $qtd_p = intval($_POST['parcelas']); - - switch ($tipoGeracao) { - case '1': - $datasVencimento = Util::mensalidadeInterna(1, $qtd_p, $diaVencimento); - break; - case '2': - $datasVencimento = Util::mensalidadeInterna(2, $qtd_p, $diaVencimento); - break; - case '3': - $datasVencimento = Util::mensalidadeInterna(3, $qtd_p, $diaVencimento); - break; - case '6': - $datasVencimento = Util::mensalidadeInterna(6, $qtd_p, $diaVencimento); - break; - default: - echo json_encode(['erro' => 'O tipo de geração é inválido.']); - exit(); - } + if (isset($_POST['tipoGeracao']) && !empty($_POST['tipoGeracao'])) { + //verificar autenticação do funcionário + require_once '../../permissao/permissao.php'; - foreach ($datasVencimento as $dataVencimento) { - $contribuicaoLog = new ContribuicaoLog(); - $contribuicaoLog - ->setValor($valor) - ->setCodigo($contribuicaoLog->gerarCodigo()) - ->setDataGeracao($dataAtual->format('Y-m-d')) - ->setDataVencimento($dataVencimento) - ->setSocio($socio); - - //Inserir na coleção - $contribuicaoLogCollection->add($contribuicaoLog); - } - } else { + session_start(); + permissao($_SESSION['id_pessoa'], 4); - // Verificar se o dia informado já passou neste mês - if ($diaVencimento <= $dataAtual->format('d')) { - // Se o dia informado já passou, começar a partir do próximo mês - $dataAtual->modify('first day of next month'); - } + //escolher qual ação tomar + $tipoGeracao = $_POST['tipoGeracao']; + + //chamar funções + require_once '../helper/Util.php'; - for ($i = 0; $i < $qtdParcelas; $i++) { - // Clonar a data atual para evitar modificar o objeto original - $dataVencimento = clone $dataAtual; + $datasVencimento; - // Adicionar os meses de acordo com o índice da parcela - $dataVencimento->modify("+{$i} month"); + $diaVencimento = ($_POST['dia']); - // Definir o dia do vencimento para o dia informado - $dataVencimento->setDate($dataVencimento->format('Y'), $dataVencimento->format('m'), $diaVencimento); + $qtd_p = intval($_POST['parcelas']); - // Ajustar a data caso o mês não tenha o dia informado (por exemplo, 30 de fevereiro) - if ($dataVencimento->format('d') != $diaVencimento) { - $dataVencimento->modify('last day of previous month'); + switch ($tipoGeracao) { + case '1': + $datasVencimento = Util::mensalidadeInterna(1, $qtd_p, $diaVencimento); + break; + case '2': + $datasVencimento = Util::mensalidadeInterna(2, $qtd_p, $diaVencimento); + break; + case '3': + $datasVencimento = Util::mensalidadeInterna(3, $qtd_p, $diaVencimento); + break; + case '6': + $datasVencimento = Util::mensalidadeInterna(6, $qtd_p, $diaVencimento); + break; + default: + echo json_encode(['erro' => 'O tipo de geração é inválido.']); + exit(); } - $contribuicaoLog = new ContribuicaoLog(); - $contribuicaoLog - ->setValor($valor) - ->setCodigo($contribuicaoLog->gerarCodigo()) - ->setDataGeracao($dataAtual->format('Y-m-d')) - ->setDataVencimento($dataVencimento->format('Y-m-d')) - ->setSocio($socio); + foreach ($datasVencimento as $dataVencimento) { + $contribuicaoLog = new ContribuicaoLog(); + $contribuicaoLog + ->setValor($valor) + ->setCodigo($contribuicaoLog->gerarCodigo()) + ->setDataGeracao($dataAtual->format('Y-m-d')) + ->setDataVencimento($dataVencimento) + ->setSocio($socio) + ->setGatewayPagamento($gatewayPagamento) + ->setMeioPagamento($meioPagamento); + + //inserir na collection o resultado do método criar de contribuicaoDao + $contribuicaoLog = $contribuicaoLogDao->criar($contribuicaoLog); + + $contribuicaoLogCollection->add($contribuicaoLog); + } + } else { - //Inserir na coleção - $contribuicaoLogCollection->add($contribuicaoLog); - } - } + // Verificar se o dia informado já passou neste mês + if ($diaVencimento <= $dataAtual->format('d')) { + // Se o dia informado já passou, começar a partir do próximo mês + $dataAtual->modify('first day of next month'); + } - try { - /*Controle de transação para que o log só seja registrado - caso o serviço de pagamento tenha sido executado*/ - $this->pdo->beginTransaction(); + for ($i = 0; $i < $qtdParcelas; $i++) { + // Clonar a data atual para evitar modificar o objeto original + $dataVencimento = clone $dataAtual; + + // Adicionar os meses de acordo com o índice da parcela + $dataVencimento->modify("+{$i} month"); + + // Definir o dia do vencimento para o dia informado + $dataVencimento->setDate($dataVencimento->format('Y'), $dataVencimento->format('m'), $diaVencimento); + + // Ajustar a data caso o mês não tenha o dia informado (por exemplo, 30 de fevereiro) + if ($dataVencimento->format('d') != $diaVencimento) { + $dataVencimento->modify('last day of previous month'); + } + + $contribuicaoLog = new ContribuicaoLog(); + $contribuicaoLog + ->setValor($valor) + ->setCodigo($contribuicaoLog->gerarCodigo()) + ->setDataGeracao($dataAtual->format('Y-m-d')) + ->setDataVencimento($dataVencimento->format('Y-m-d')) + ->setSocio($socio) + ->setGatewayPagamento($gatewayPagamento) + ->setMeioPagamento($meioPagamento); - foreach ($contribuicaoLogCollection as $contribuicaoLog) { - $contribuicaoLogDao = new ContribuicaoLogDAO($this->pdo); - $contribuicaoLogDao->criar($contribuicaoLog); + //inserir na collection o resultado do método criar de contribuicaoDao + $contribuicaoLog = $contribuicaoLogDao->criar($contribuicaoLog); + + $contribuicaoLogCollection->add($contribuicaoLog); + } } //Registrar na tabela de socio_log @@ -293,13 +299,20 @@ public function criarCarne() $socioDao->registrarLog($contribuicaoLog->getSocio(), $mensagem); //Chamada do método de serviço de pagamento requisitado - $caminhoCarne = $servicoPagamento->gerarCarne($contribuicaoLogCollection); - if (!$caminhoCarne || empty($caminhoCarne)) { + + //Método deverá retornar o caminho do carne e um array de contribuicões log + $resultado = $servicoPagamento->gerarCarne($contribuicaoLogCollection); + if (!$resultado || empty($resultado)) { $this->pdo->rollBack(); } else { + //loop foreach para alterar o código no banco de dados das respectivas contribuições recebidas + foreach($resultado['contribuicoes'] as $contribuicao){ + $contribuicaoLogDao->alterarCodigoPorId($contribuicao->getCodigo(), $contribuicao->getId()); + } + $this->pdo->commit(); - echo json_encode(['link' => WWW . 'html/apoio/' . $caminhoCarne]); + echo json_encode(['link' => WWW . 'html/apoio/' . $resultado['link']]); } } catch (PDOException $e) { //implementar tratamento de erro @@ -339,6 +352,7 @@ public function criarQrCode() $gatewayPagamentoDao = new GatewayPagamentoDAO(); $gatewayPagamentoArray = $gatewayPagamentoDao->buscarPorId($meioPagamento->getGatewayId()); $gatewayPagamento = new GatewayPagamento($gatewayPagamentoArray['plataforma'], $gatewayPagamentoArray['endPoint'], $gatewayPagamentoArray['token'], $gatewayPagamentoArray['status']); + $gatewayPagamento->setId($meioPagamento->getGatewayId()); //Requisição dinâmica e instanciação da classe com base no nome do gateway de pagamento $requisicaoServico = '../service/' . $gatewayPagamento->getNome() . $formaPagamento . 'Service' . '.php'; @@ -374,7 +388,9 @@ public function criarQrCode() ->setCodigo($contribuicaoLog->gerarCodigo()) ->setDataGeracao($dataGeracao) ->setDataVencimento($dataVencimento) - ->setSocio($socio); + ->setSocio($socio) + ->setGatewayPagamento($gatewayPagamento) + ->setMeioPagamento($meioPagamento); try { /*Controle de transação para que o log só seja registrado diff --git a/html/apoio/controller/SocioController.php b/html/apoio/controller/SocioController.php index bca86d7e..f55b67d2 100755 --- a/html/apoio/controller/SocioController.php +++ b/html/apoio/controller/SocioController.php @@ -2,8 +2,212 @@ require_once '../model/Socio.php'; require_once '../dao/SocioDAO.php'; require_once '../helper/Util.php'; +require_once '../dao/ConexaoDAO.php'; class SocioController { + private PDO $pdo; + + public function __construct() + { + $this->pdo = ConexaoDAO::conectar(); + } + + public function criarSocio() + { + $dados = $this->extrairPost(); + $socio = new Socio(); + $socio + ->setNome($dados['nome']) + ->setDataNascimento($dados['dataNascimento']) + ->setTelefone($dados['telefone']) + ->setEmail($dados['email']) + ->setEstado($dados['uf']) + ->setCidade($dados['cidade']) + ->setBairro($dados['bairro']) + ->setComplemento($dados['complemento']) + ->setCep($dados['cep']) + ->setNumeroEndereco($dados['numero']) + ->setLogradouro($dados['rua']) + ->setDocumento($dados['cpf']) + ->setIbge($dados['ibge']) + ->setValor($dados['valor']); + + try { + $socioDao = new SocioDAO(); + $socioDao->criarSocio($socio); + + http_response_code(200); + echo json_encode(['mensagem' => 'Sócio criado com sucesso!']); + } catch (PDOException $e) { + http_response_code(500); + echo json_encode(['erro' => $e->getMessage()]); + } + } + + public function atualizarSocio() + { + $dados = $this->extrairPost(); + $socio = new Socio(); + $socio + ->setNome($dados['nome']) + ->setDataNascimento($dados['dataNascimento']) + ->setTelefone($dados['telefone']) + ->setEmail($dados['email']) + ->setEstado($dados['uf']) + ->setCidade($dados['cidade']) + ->setBairro($dados['bairro']) + ->setComplemento($dados['complemento']) + ->setCep($dados['cep']) + ->setNumeroEndereco($dados['numero']) + ->setLogradouro($dados['rua']) + ->setDocumento($dados['cpf']) + ->setIbge($dados['ibge']) + ->setValor($dados['valor']); + + try { + $socioDao = new SocioDAO($this->pdo); + + //Verifica se o sócio é um funcionário ou atendido + if ($socioDao->verificarInternoPorDocumento($socio->getDocumento())) { + http_response_code(403); + echo json_encode(['erro' => 'Você não possuí permissão para alterar os dados desse CPF']); + exit(); + } + + $this->pdo->beginTransaction(); + $socioDao->registrarLogPorDocumento($socio->getDocumento(), 'Atualização recente'); + + if($socioDao->atualizarSocio($socio)){ + $this->pdo->commit(); + http_response_code(200); + echo json_encode(['mensagem' => 'Atualizado com sucesso!']); + exit(); + }else{ + $this->pdo->rollBack(); + http_response_code(500); + echo json_encode(['erro' => 'Erro ao atualizar sócio no sistema']); + exit(); + } + + } catch (PDOException $e) { + http_response_code(500); + echo json_encode(['erro' => $e->getMessage()]); + exit(); + } + } + + /** + * Pega os dados do formulário e retorna um array caso todas as informações passem pelas validações + */ + function extrairPost() + { + //extrair dados da requisição (considerar separar em uma função própria) + $cpf = trim(filter_input(INPUT_POST, 'documento_socio')); + $nome = trim(filter_input(INPUT_POST, 'nome')); + $telefone = trim(filter_input(INPUT_POST, 'telefone')); + $dataNascimento = trim(filter_input(INPUT_POST, 'data_nascimento')); + $cep = trim(filter_input(INPUT_POST, 'cep')); + $rua = trim(filter_input(INPUT_POST, 'rua')); + $bairro = trim(filter_input(INPUT_POST, 'bairro')); + $uf = trim(filter_input(INPUT_POST, 'uf')); + $cidade = trim(filter_input(INPUT_POST, 'cidade')); + $complemento = trim(filter_input(INPUT_POST, 'complemento')); + $numero = trim(filter_input(INPUT_POST, 'numero')); + $ibge = trim(filter_input(INPUT_POST, 'ibge')); + $email = trim(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL)); + $valor = trim(filter_input(INPUT_POST, 'valor')); + + //validar dados (considerar separar em uma função própria) + try { + //validação do CPF + require_once('../helper/Util.php'); + $util = new Util(); + + if (!$util->validarCPF($cpf)) { + throw new InvalidArgumentException('O CPF informado não é válido'); + } + + //validação do nome + if (!$nome || strlen($nome) < 3) { + throw new InvalidArgumentException('O nome informado não pode ser vazio'); + } + + //validação do telefone + if (!$telefone || strlen($telefone) != 14) { //considerar melhorar a validação posteriormente + throw new InvalidArgumentException('O telefone informado não está no formato válido'); + } + + //validação da data de nascimento + $hoje = new DateTime(); + $hoje = $hoje->format('Y-m-d'); + + if ($dataNascimento > $hoje) { + throw new InvalidArgumentException('A data de nascimento não pode ser maior que a data atual'); + } + + //validação do CEP + if (!$cep || strlen($cep) != 9) { + throw new InvalidArgumentException('O CEP informado não está no formato válido'); + } + + //validação da rua + if (!$rua || empty($rua)) { + throw new InvalidArgumentException('A rua informada não pode ser vazia'); + } + + //validação do bairro + if (!$bairro || empty($bairro)) { + throw new InvalidArgumentException('O bairro informado não pode ser vazio'); + } + + //validação do estado + if (!$uf || strlen($uf) != 2) { + throw new InvalidArgumentException('O Estado informada não pode ser vazio'); + } + + //validação da cidade + if (!$cidade || empty($cidade)) { + throw new InvalidArgumentException('A cidade informada não pode ser vazia'); + } + + //validação do número da residência + if (!$numero || empty($numero)) { + throw new InvalidArgumentException('O número da residência informada não pode ser vazio'); + } + + //validação do email + if (!$email || empty($email)) { + throw new InvalidArgumentException('O email informado não está em um formato válido'); + } + + //validação do valor + if (!$valor || $valor < 30) { //Pegar o valor de maneira dinâmica posteriormente + throw new InvalidArgumentException('O valor informado deve ser de no mínimo 30 reais.'); + } + } catch (InvalidArgumentException $e) { + http_response_code(400); + echo json_encode(['erro' => $e->getMessage()]); + exit(); + } + + return [ + 'cpf' => $cpf, + 'nome' => $nome, + 'telefone' => $telefone, + 'dataNascimento' => $dataNascimento, + 'cep' => $cep, + 'rua' => $rua, + 'bairro' => $bairro, + 'uf' => $uf, + 'cidade' => $cidade, + 'complemento' => $complemento, + 'numero' => $numero, + 'ibge' => $ibge, + 'email' => $email, + 'valor' => $valor, + ]; + } + /** * Extraí o documento de um sócio da requisição e retorna os dados pertecentes a esse sócio. */ diff --git a/html/apoio/controller/control.php b/html/apoio/controller/control.php index e07bf936..5120b987 100755 --- a/html/apoio/controller/control.php +++ b/html/apoio/controller/control.php @@ -12,6 +12,8 @@ [ 'exibirBoletosPorCpf', 'buscarPorDocumento', + 'criarSocio', + 'atualizarSocio', ]; //Blocks execution for unauthorized access diff --git a/html/apoio/dao/ContribuicaoLogDAO.php b/html/apoio/dao/ContribuicaoLogDAO.php index 82a55832..5c9ec627 100755 --- a/html/apoio/dao/ContribuicaoLogDAO.php +++ b/html/apoio/dao/ContribuicaoLogDAO.php @@ -20,7 +20,9 @@ public function __construct(PDO $pdo = null) public function criar(ContribuicaoLog $contribuicaoLog){ $sqlInserirContribuicaoLog = "INSERT INTO contribuicao_log ( - id_socio, + id_socio, + id_gateway, + id_meio_pagamento, codigo, valor, data_geracao, @@ -29,6 +31,8 @@ public function criar(ContribuicaoLog $contribuicaoLog){ ) VALUES ( :idSocio, + :idGateway, + :idMeioPagamento, :codigo, :valor, :dataGeracao, @@ -39,6 +43,8 @@ public function criar(ContribuicaoLog $contribuicaoLog){ $stmt = $this->pdo->prepare($sqlInserirContribuicaoLog); $stmt->bindParam(':idSocio', $contribuicaoLog->getSocio()->getId()); + $stmt->bindParam(':idGateway', $contribuicaoLog->getGatewayPagamento()->getId()); + $stmt->bindParam(':idMeioPagamento', $contribuicaoLog->getMeioPagamento()->getId()); $stmt->bindParam(':codigo', $contribuicaoLog->getCodigo()); $stmt->bindParam(':valor', $contribuicaoLog->getValor()); $stmt->bindParam(':dataGeracao', $contribuicaoLog->getDataGeracao()); @@ -46,6 +52,21 @@ public function criar(ContribuicaoLog $contribuicaoLog){ $stmt->bindParam(':statusPagamento', $contribuicaoLog->getStatusPagamento()); $stmt->execute(); + + $ultimoId = $this->pdo->lastInsertId(); + $contribuicaoLog->setId($ultimoId); + + return $contribuicaoLog; + } + + public function alterarCodigoPorId($codigo, $id){ + $sqlPagarPorId = "UPDATE contribuicao_log SET codigo =:codigo WHERE id=:id"; + + $stmt = $this->pdo->prepare($sqlPagarPorId); + $stmt->bindParam(':codigo', $codigo); + $stmt->bindParam(':id', $id); + + $stmt->execute(); } public function pagarPorId($id){ diff --git a/html/apoio/dao/MeioPagamentoDAO.php b/html/apoio/dao/MeioPagamentoDAO.php index 490a03f1..aed0a56b 100755 --- a/html/apoio/dao/MeioPagamentoDAO.php +++ b/html/apoio/dao/MeioPagamentoDAO.php @@ -52,7 +52,7 @@ public function buscaTodos() * Retorna o meio de pagamento com nome equivalente ao passado como parâmetro */ public function buscarPorNome(string $nome){ - $sqlBuscarPorNome = 'SELECT meio, id_plataforma, status FROM contribuicao_meioPagamento WHERE meio=:nome'; + $sqlBuscarPorNome = 'SELECT id, meio, id_plataforma, status FROM contribuicao_meioPagamento WHERE meio=:nome'; $stmt = $this->pdo->prepare($sqlBuscarPorNome); $stmt->bindParam(':nome', $nome); @@ -64,7 +64,10 @@ public function buscarPorNome(string $nome){ $meioPagamentoArray = $stmt->fetch(PDO::FETCH_ASSOC); - return new MeioPagamento($meioPagamentoArray['meio'], $meioPagamentoArray['id_plataforma'], $meioPagamentoArray['status']); + $meioPagamento = new MeioPagamento($meioPagamentoArray['meio'], $meioPagamentoArray['id_plataforma'], $meioPagamentoArray['status']); + $meioPagamento->setId($meioPagamentoArray['id']); + + return $meioPagamento; } /** diff --git a/html/apoio/dao/SocioDAO.php b/html/apoio/dao/SocioDAO.php index 88088a0e..be54adc9 100755 --- a/html/apoio/dao/SocioDAO.php +++ b/html/apoio/dao/SocioDAO.php @@ -4,23 +4,26 @@ //requisitar model require_once '../model/Socio.php'; -class SocioDAO{ +class SocioDAO +{ private $pdo; public function __construct(PDO $pdo = null) { - if(is_null($pdo)){ + if (is_null($pdo)) { $this->pdo = ConexaoDAO::conectar(); - }else{ + } else { $this->pdo = $pdo; } } - public function montarSocio($socioArray){ + public function montarSocio($socioArray) + { $socio = new Socio(); $socio ->setId($socioArray['id_socio']) ->setNome($socioArray['nome']) + ->setDataNascimento($socioArray['data_nascimento']) ->setTelefone($socioArray['telefone']) ->setEmail($socioArray['email']) ->setEstado($socioArray['estado']) @@ -36,11 +39,168 @@ public function montarSocio($socioArray){ return $socio; } - public function buscarPorId($id){ - $sqlBuscaPorDocumento = - "SELECT + public function criarSocio(Socio $socio) + { + $this->pdo->beginTransaction(); + + //criar pessoa + $sqlPessoa = 'INSERT INTO pessoa(cpf, nome, telefone, data_nascimento, cep, estado, cidade, bairro, logradouro, numero_endereco, complemento, ibge) VALUES(:cpf, :nome, :telefone, :dataNascimento, :cep, :estado, :cidade, :bairro, :logradouro, :numeroEndereco, :complemento, :ibge)'; + + $stmtPessoa = $this->pdo->prepare($sqlPessoa); + + $stmtPessoa->bindParam(':cpf', $socio->getDocumento()); + $stmtPessoa->bindParam(':nome', $socio->getNome()); + $stmtPessoa->bindParam(':telefone', $socio->getTelefone()); + $stmtPessoa->bindParam(':dataNascimento', $socio->getDataNascimento()); + $stmtPessoa->bindParam(':cep', $socio->getCep()); + $stmtPessoa->bindParam(':estado', $socio->getEstado()); + $stmtPessoa->bindParam(':cidade', $socio->getCidade()); + $stmtPessoa->bindParam(':bairro', $socio->getBairro()); + $stmtPessoa->bindParam(':logradouro', $socio->getLogradouro()); + $stmtPessoa->bindParam(':numeroEndereco', $socio->getNumeroEndereco()); + $stmtPessoa->bindParam(':complemento', $socio->getComplemento()); + $stmtPessoa->bindParam(':ibge', $socio->getIbge()); + + $stmtPessoa->execute(); + $idPessoa = $this->pdo->lastInsertId(); + + //criar socio + $idSocioStatus = 3; //Define o status do sócio como Inativo temporariamente + + $tagSolicitante = $this->pdo->query("SELECT * FROM socio_tag WHERE tag='Solicitante'")->fetch(PDO::FETCH_ASSOC); + + $idSocioTag = $tagSolicitante['id_sociotag']; //Define o grupo do sócio como Solicitante + + $sqlSocio = 'INSERT INTO socio(id_pessoa, id_sociostatus, id_sociotipo, id_sociotag, email, valor_periodo, data_referencia) VALUES(:idPessoa, :idSocioStatus, :idSocioTipo, :idSocioTag, :email, :valor, :dataReferencia)'; + + $stmtSocio = $this->pdo->prepare($sqlSocio); + + $periodicidade = 0; + $dataReferencia = new DateTime(); + $dataReferencia = $dataReferencia->format('Y-m-d'); + + $stmtSocio->bindParam(':idPessoa', $idPessoa); + $stmtSocio->bindParam(':idSocioStatus', $idSocioStatus); + $stmtSocio->bindParam(':idSocioTipo', $periodicidade); + $stmtSocio->bindParam(':idSocioTag', $idSocioTag); + $stmtSocio->bindParam(':email', $socio->getEmail()); + $stmtSocio->bindParam(':valor', $socio->getValor()); + $stmtSocio->bindParam(':dataReferencia', $dataReferencia); + + $stmtSocio->execute(); + + //registrar no socio_log + $idSocio = $this->pdo->lastInsertId(); + + $sqlRegistrarSocioLog = "INSERT INTO socio_log (id_socio, descricao) + VALUES (:idSocio,'Inscrição recente')"; + + $stmtSocioLog = $this->pdo->prepare($sqlRegistrarSocioLog); + $stmtSocioLog->bindParam(':idSocio', $idSocio); + + if ($stmtSocioLog->execute()) { + $this->pdo->commit(); + } else { + $this->pdo->rollBack(); + http_response_code(500); + echo json_encode(['erro' => 'Erro ao cadastrar sócio no sistema']); + exit(); + } + } + + public function atualizarSocio(Socio $socio){ + //atualizar os dados de pessoa + $sqlAtualizarPessoa = + 'UPDATE pessoa + SET + nome=:nome, + telefone=:telefone, + data_nascimento=:dataNascimento, + cep=:cep, + estado=:estado, + cidade=:cidade, + bairro=:bairro, + logradouro=:logradouro, + numero_endereco=:numeroEndereco, + complemento=:complemento, + ibge=:ibge + WHERE cpf=:cpf'; + + $stmtPessoa = $this->pdo->prepare($sqlAtualizarPessoa); + + $stmtPessoa->bindParam(':nome', $socio->getNome()); + $stmtPessoa->bindParam(':telefone', $socio->getTelefone()); + $stmtPessoa->bindParam(':dataNascimento', $socio->getDataNascimento()); + $stmtPessoa->bindParam(':cep', $socio->getCep()); + $stmtPessoa->bindParam(':estado', $socio->getEstado()); + $stmtPessoa->bindParam(':cidade', $socio->getCidade()); + $stmtPessoa->bindParam(':bairro', $socio->getBairro()); + $stmtPessoa->bindParam(':logradouro', $socio->getLogradouro()); + $stmtPessoa->bindParam(':numeroEndereco', $socio->getNumeroEndereco()); + $stmtPessoa->bindParam(':complemento', $socio->getComplemento()); + $stmtPessoa->bindParam(':ibge', $socio->getIbge()); + $stmtPessoa->bindParam(':cpf', $socio->getDocumento()); + + $stmtPessoa->execute(); + + //atualizar os dados de socio + + //verificar se possuí o status de Ativo + $sqlBuscaAtivo = "SELECT s.id_sociotag FROM socio s JOIN pessoa p ON (s.id_pessoa=p.id_pessoa) WHERE cpf=:cpf AND s.id_sociostatus =0"; + + $stmtStatusAtivo = $this->pdo->prepare($sqlBuscaAtivo); + $stmtStatusAtivo->bindParam(':cpf', $socio->getDocumento()); + $stmtStatusAtivo->execute(); + + if ($stmtStatusAtivo->rowCount() > 0) { + $idSocioTag = $stmtStatusAtivo->fetch(PDO::FETCH_ASSOC)['id_sociotag']; + } else { + $tagSolicitante = $this->pdo->query("SELECT * FROM socio_tag WHERE tag='Solicitante'")->fetch(PDO::FETCH_ASSOC); + $idSocioTag = $tagSolicitante['id_sociotag']; //Define o grupo do sócio como Solicitante + } + + $sqlAtualizarSocio = + 'UPDATE socio s + JOIN pessoa p ON s.id_pessoa = p.id_pessoa + SET + s.email = :email, + s.valor_periodo = :valor, + s.id_sociotag =:tag + WHERE p.cpf = :cpf'; + + $stmtSocio = $this->pdo->prepare($sqlAtualizarSocio); + + $stmtSocio->bindParam(':email', $socio->getEmail()); + $stmtSocio->bindParam(':valor', $socio->getValor()); + $stmtSocio->bindParam(':cpf', $socio->getDocumento()); + $stmtSocio->bindParam(':tag', $idSocioTag); + + return $stmtSocio->execute(); + + } + + public function verificarInternoPorDocumento($documento) + { + $sqlVerificarInterno = 'SELECT p.id_pessoa FROM pessoa p JOIN socio s ON (s.id_pessoa=p.id_pessoa) LEFT JOIN atendido a ON(a.pessoa_id_pessoa=p.id_pessoa) LEFT JOIN funcionario f ON(f.id_pessoa=p.id_pessoa) WHERE p.cpf=:cpf AND (a.pessoa_id_pessoa IS NOT NULL OR f.id_pessoa IS NOT NULL)'; + + $stmt = $this->pdo->prepare($sqlVerificarInterno); + $stmt->bindParam(':cpf', $documento); + $stmt->execute(); + + if ($stmt->rowCount() > 0) { + return true; + } + + return false; + } + + public function buscarPorId($id) + { + $sqlBuscaPorDocumento = + "SELECT pessoa.id_pessoa, - pessoa.nome, + pessoa.nome, + pessoa.data_nascimento, pessoa.telefone, pessoa.cep, pessoa.estado, @@ -61,7 +221,7 @@ public function buscarPorId($id){ $stmt->execute(); - if($stmt->rowCount() === 0){ + if ($stmt->rowCount() === 0) { return null; } @@ -72,9 +232,10 @@ public function buscarPorId($id){ return $socio; } - public function buscarPorDocumento($documento){ - $sqlBuscaPorDocumento = - "SELECT + public function buscarPorDocumento($documento) + { + $sqlBuscaPorDocumento = + "SELECT pessoa.id_pessoa, pessoa.nome, pessoa.telefone, @@ -97,7 +258,7 @@ public function buscarPorDocumento($documento){ $stmt->execute(); - if($stmt->rowCount() === 0){ + if ($stmt->rowCount() === 0) { return null; } @@ -108,7 +269,8 @@ public function buscarPorDocumento($documento){ return $socio; } - public function registrarLog(Socio $socio, string $mensagem){ + public function registrarLog(Socio $socio, string $mensagem) + { $sqlRegistrarSocioLog = "INSERT INTO socio_log (id_socio, descricao) VALUES (:idSocio, :mensagem)"; @@ -118,4 +280,21 @@ public function registrarLog(Socio $socio, string $mensagem){ return $stmt->execute(); } -} \ No newline at end of file + + public function registrarLogPorDocumento(string $documento, string $mensagem) + { + $sqlRegistrarSocioLog = "INSERT INTO socio_log (id_socio, descricao) + VALUES ( + (SELECT s.id_socio + FROM socio s + JOIN pessoa p ON s.id_pessoa = p.id_pessoa + WHERE p.cpf =:cpf), + :mensagem + )"; + + $stmtSocioLog = $this->pdo->prepare($sqlRegistrarSocioLog); + $stmtSocioLog->bindParam(':cpf', $documento); + $stmtSocioLog->bindParam(':mensagem', $mensagem); + $stmtSocioLog->execute(); + } +} diff --git a/html/apoio/helper/Util.php b/html/apoio/helper/Util.php index 30945e01..abe6a2cf 100755 --- a/html/apoio/helper/Util.php +++ b/html/apoio/helper/Util.php @@ -86,4 +86,55 @@ public static function listarArquivos(string $diretorio) return $arquivos; } + + public static function validarCPF(string $cpf){ + //Limpar formatação + $cpfLimpo = preg_replace('/[^0-9]/', '', $cpf); + + //Validação do tamanho da string informada + if (strlen($cpfLimpo) != 11) { + return false; + } + + // Validação de CPFs conhecidos como inválidos + if (preg_match('/(\d)\1{10}/', $cpfLimpo)) { + return false; + } + + //Validação do primeiro dígito verificador + $soma = 0; + $resto = 0; + + for ($i = 0; $i < 9; $i++) { // Cálculo da soma + $soma += $cpfLimpo[$i] * (10 - $i); + } + + $resto = $soma % 11; + + $digitoVerificador1 = $resto < 2 ? 0 : 11 - $resto; + + if ($digitoVerificador1 != $cpfLimpo[9]) { + return false; + } + + //Validação do segundo dígito verificador + $soma = 0; + $resto = 0; + //$digitoVerificador2 = 0; + + for ($i = 0; $i < 10; $i++) { // Cálculo da soma + $soma += $cpfLimpo[$i] * (11 - $i); + } + + $resto = $soma % 11; + + $digitoVerificador2 = $resto < 2 ? 0 : 11 - $resto; + + if ($digitoVerificador2 != $cpfLimpo[10]) { + return false; + } + + //Retornar resultado + return true; + } } diff --git a/html/apoio/model/ContribuicaoLog.php b/html/apoio/model/ContribuicaoLog.php index afa0f812..134abc07 100755 --- a/html/apoio/model/ContribuicaoLog.php +++ b/html/apoio/model/ContribuicaoLog.php @@ -1,5 +1,7 @@ gatewayPagamento; + } + + /** + * Set the value of gatewayPagamento + * + * @return self + */ + public function setGatewayPagamento(GatewayPagamento $gatewayPagamento) + { + $this->gatewayPagamento = $gatewayPagamento; + + return $this; + } + + /** + * Get the value of meioPagamento + */ + public function getMeioPagamento() + { + return $this->meioPagamento; + } + + /** + * Set the value of meioPagamento + * + * @return self + */ + public function setMeioPagamento(MeioPagamento $meioPagamento) + { + $this->meioPagamento = $meioPagamento; + + return $this; + } } diff --git a/html/apoio/model/Socio.php b/html/apoio/model/Socio.php index 30b4d2cb..d1bdf2ec 100755 --- a/html/apoio/model/Socio.php +++ b/html/apoio/model/Socio.php @@ -3,6 +3,7 @@ class Socio implements JsonSerializable{ private $id; private $nome; + private $dataNascimento; private $telefone; private $email; private $estado; @@ -13,6 +14,8 @@ class Socio implements JsonSerializable{ private $numeroEndereco; private $logradouro; private $documento; + private $ibge; + private $valor; //métodos de lógica @@ -21,6 +24,7 @@ public function jsonSerialize(): mixed return [ 'id' => $this->id, 'nome' => $this->nome, + 'dataNascimento' => $this->dataNascimento, 'telefone' => $this->telefone, 'email' => $this->email, 'estado' => $this->estado, @@ -275,4 +279,64 @@ public function setDocumento($documento) return $this; } + + /** + * Get the value of dataNascimento + */ + public function getDataNascimento() + { + return $this->dataNascimento; + } + + /** + * Set the value of dataNascimento + * + * @return self + */ + public function setDataNascimento($dataNascimento) + { + $this->dataNascimento = $dataNascimento; + + return $this; + } + + /** + * Get the value of ibge + */ + public function getIbge() + { + return $this->ibge; + } + + /** + * Set the value of ibge + * + * @return self + */ + public function setIbge($ibge) + { + $this->ibge = $ibge; + + return $this; + } + + /** + * Get the value of valor + */ + public function getValor() + { + return $this->valor; + } + + /** + * Set the value of valor + * + * @return self + */ + public function setValor($valor) + { + $this->valor = $valor; + + return $this; + } } \ No newline at end of file diff --git a/html/apoio/public/js/boleto.js b/html/apoio/public/js/boleto.js index 76f44d70..6bfd57cd 100644 --- a/html/apoio/public/js/boleto.js +++ b/html/apoio/public/js/boleto.js @@ -1,3 +1,5 @@ +let acao = 'boleto'; + function buscarSocio() { const documento = pegarDocumento(); @@ -27,11 +29,15 @@ function buscarSocio() { //Exibir o sócio console.log(data); formAutocomplete(data.resultado); - }else{//Enviar para a página de confirmação de geração de boletos + acao = 'atualizar'; + alternarPaginas('pag3', 'pag2'); + } else {//Enviar para a página de confirmação de geração de boletos alternarPaginas('pag5', 'pag2'); } } else { console.log(data.resultado); + acao = 'cadastrar'; + alternarPaginas('pag3', 'pag2'); } //alternarPaginas('pag2'); @@ -43,7 +49,56 @@ function buscarSocio() { console.log("Consulta realizada"); } +async function decidirAcao() { + switch (acao) { + case 'boleto': gerarBoleto(); break; + case 'cadastrar': await cadastrarSocio(); gerarBoleto(); break;//colocar chamada para função de cadastrar sócio + case 'atualizar': await atualizarSocio(); gerarBoleto(); break;//colocar chamada para função de atualizar sócio + default: console.log('Ação indefinida'); + } +} + +function gerarBoleto() { + const form = document.getElementById('formulario'); + const formData = new FormData(form); + + const documento = pegarDocumento(); + + formData.append('nomeClasse', 'ContribuicaoLogController'); + formData.append('metodo', 'criarBoleto'); + formData.append('documento_socio', documento); + + fetch("../controller/control.php", { + method: "POST", + body: formData + }) + .then(response => { + if (!response.ok) { + throw new Error("Erro na requisição: " + response.status); + } + return response.json(); // Converte a resposta para JSON + }) + .then(resposta => { + if (resposta.link) { + console.log(resposta.link); + // Redirecionar o usuário para o link do boleto em uma nova aba + window.open(resposta.link, '_blank'); + } else { + alert("Ops! Ocorreu um problema na geração da sua forma de pagamento, tente novamente, se o erro persistir contate o suporte."); + } + + }) + .catch(error => { + console.error("Erro:", error); + }); +} + configurarAvancaValor(verificarValor); configurarVoltaValor(); +configurarVoltaCpf(); +configurarVoltaContato(); +configurarAvancaEndereco(verificarEndereco); +configurarAvancaContato(verificarContato); +configurarAvancaTerminar(decidirAcao); configurarMudancaOpcao(alternarPfPj); configurarConsulta(buscarSocio); \ No newline at end of file diff --git a/html/apoio/public/js/util.js b/html/apoio/public/js/util.js index f1ece579..bdb751e4 100644 --- a/html/apoio/public/js/util.js +++ b/html/apoio/public/js/util.js @@ -30,7 +30,8 @@ function configurarMudancaOpcao(funcao) { */ function configurarConsulta(funcao) { const btnConsulta = document.getElementById("consultar-btn"); - btnConsulta.addEventListener("click", function () { + btnConsulta.addEventListener("click", function (ev) { + ev.preventDefault(); funcao(); }) } @@ -119,7 +120,8 @@ function alternarPaginas(idProxima, idAtual) { */ function configurarConsulta(funcao) { const btnConsulta = document.getElementById("consultar-btn"); - btnConsulta.addEventListener("click", function () { + btnConsulta.addEventListener("click", function (ev) { + ev.preventDefault(); funcao(); }) } @@ -145,9 +147,9 @@ function verificarValor(valor) { function configurarAvancaValor(funcao) { const btnAvancaValor = document.getElementById('avanca-valor'); - btnAvancaValor.addEventListener('click', () => { + btnAvancaValor.addEventListener('click', (ev) => { const valor = document.getElementById('valor').value; - + ev.preventDefault(); if (!funcao(valor)) { alert('O valor informado está abaixo do mínimo permitido.'); return; @@ -160,28 +162,80 @@ function configurarAvancaValor(funcao) { /** * Configura o comportamento do botão volta-valor */ -function configurarVoltaValor(){ +function configurarVoltaValor() { const btnVoltaValor = document.getElementById('volta-valor'); - btnVoltaValor.addEventListener('click', ()=>{ + btnVoltaValor.addEventListener('click', (ev) => { + ev.preventDefault(); alternarPaginas('pag1', 'pag2'); }); } +function configurarVoltaCpf() { + const btnVoltaCpf = document.getElementById('volta-cpf'); + btnVoltaCpf.addEventListener('click', (ev) => { + ev.preventDefault(); + alternarPaginas('pag2', 'pag3'); + }); +} + +function configurarVoltaContato() { + const btnVoltaContato = document.getElementById('volta-contato'); + btnVoltaContato.addEventListener('click', (ev) => { + ev.preventDefault(); + alternarPaginas('pag3', 'pag4'); + }); +} + +function configurarAvancaContato(funcao) { + const btnAvancaContato = document.getElementById('avanca-contato'); + btnAvancaContato.addEventListener('click', (ev) => { + ev.preventDefault(); + if (!funcao()) { + return; + } + + alternarPaginas('pag4', 'pag3'); + }) +} + +function configurarAvancaEndereco(funcao) { + const btnAvancaEndereco = document.getElementById('avanca-endereco'); + btnAvancaEndereco.addEventListener('click', (ev) => { + ev.preventDefault(); + if (!funcao()) { + return; + } + + alternarPaginas('pag5', 'pag4'); + }); +} + +function configurarAvancaTerminar(funcao) { + const btnAvancaTerminar = document.getElementById('avanca-terminar'); + btnAvancaTerminar.addEventListener('click', (ev) => { + ev.preventDefault(); + btnAvancaTerminar.disabled = true; + btnAvancaTerminar.classList.add('disabled'); + setLoader(btnAvancaTerminar); + funcao(); + }); +} + /** * Verifica se alguma propriedade de um objeto do tipo Socio está vazia */ -function verificarSocio({bairro, cep, cidade, complemento, documento, email, estado, id, logradouro, nome, numeroEndereco, telefone}){ +function verificarSocio({ bairro, cep, cidade, complemento, documento, email, estado, id, logradouro, nome, numeroEndereco, telefone }) { //verificar propriedades - if(!bairro || bairro.length < 1){ + if (!bairro || bairro.length < 1) { return false; } - if(!cep || cep.length < 1){ + if (!cep || cep.length < 1) { return false; } - if(!cidade || cidade.length < 1){ + if (!cidade || cidade.length < 1) { return false; } @@ -189,35 +243,169 @@ function verificarSocio({bairro, cep, cidade, complemento, documento, email, est return false; }*/ - if(!documento || documento.length < 1){ + if (!documento || documento.length < 1) { + return false; + } + + if (!email || email.length < 1) { + return false; + } + + if (!estado || estado.length < 1) { + return false; + } + + if (!id || id.length < 1) { + return false; + } + + if (!logradouro || logradouro.length < 1) { + return false; + } + + if (!nome || nome.length < 1) { + return false; + } + + if (!numeroEndereco || numeroEndereco.length < 1) { + return false; + } + + if (!telefone || telefone.length < 1) { + return false; + } + + return true; +} + +async function cadastrarSocio() { + const form = document.getElementById('formulario'); + const formData = new FormData(form); + + const documento = pegarDocumento(); + + formData.append('nomeClasse', 'SocioController'); + formData.append('metodo', 'criarSocio'); + formData.append('documento_socio', documento); + + try { + const response = await fetch("../controller/control.php", { + method: "POST", + body: formData + }); + + if (!response.ok) { + throw new Error("Erro na requisição: " + response.status); + } + + const resposta = await response.json(); // Converte a resposta para JSON + + if (resposta.mensagem) { + console.log(resposta.mensagem); + } else { + alert("Ops! Ocorreu um problema durante o seu cadastro, se o erro persistir contate o suporte."); + } + } catch (error) { + console.error("Erro:", error); + } +} + +async function atualizarSocio() { + const form = document.getElementById('formulario'); + const formData = new FormData(form); + + const documento = pegarDocumento(); + + formData.append('nomeClasse', 'SocioController'); + formData.append('metodo', 'atualizarSocio'); + formData.append('documento_socio', documento); + + try { + const response = await fetch("../controller/control.php", { + method: "POST", + body: formData + }); + + if (!response.ok) { + throw new Error("Erro na requisição: " + response.status); + } + + const resposta = await response.json(); // Converte a resposta para JSON + + if (resposta.mensagem) { + console.log(resposta.mensagem); + } else { + alert("Ops! Ocorreu um problema durante o seu cadastro, se o erro persistir contate o suporte."); + } + } catch (error) { + console.error("Erro:", error); + } +} + +function verificarEndereco() { + const cep = document.getElementById('cep').value; + const rua = document.getElementById('rua').value; + const numeroEndereco = document.getElementById('numero'); + const bairro = document.getElementById('bairro'); + const uf = document.getElementById('uf'); + const cidade = document.getElementById('cidade'); + + if (!cep || cep.length != 9) { + alert('O CEP informado não está no formato válido'); return false; } - if(!email || email.length < 1){ + if (!rua || rua.length < 1) { + alert('A rua não pode estar vazia.'); return false; } - if(!estado || estado.length < 1){ + if (!numeroEndereco || numeroEndereco.length < 1) { + alert('O número de endereço não pode estar vazio.'); return false; } - if(!id || id.length < 1){ + if (!bairro || bairro.length < 1) { + alert('O bairro não pode estar vazio.'); return false; } - if(!logradouro || logradouro.length < 1){ + if (!uf || uf.length < 1) { + alert('O estado não pode estar vazio.'); return false; } - if(!nome || nome.length < 1){ + if (!cidade || cidade.length < 1) { + alert('A cidade não pode estar vazia.'); return false; } - if(!numeroEndereco || numeroEndereco.length < 1){ + return true; +} + +function verificarContato() { + const nome = document.getElementById('nome').value; + const dataNascimento = document.getElementById('data_nascimento').value; + const email = document.getElementById('email').value; + const telefone = document.getElementById('telefone').value; + + if (!nome || nome.length < 3) { + alert('O nome não pode estar vazio.'); return false; } - if(!telefone || telefone.length < 1){ + if (!dataNascimento) { + alert('A data de nascimento não pode estar vazia'); + return false; + } + + if (!email) { + alert('O e-mail não pode estar vazio.'); + return false; + } + + if (!telefone) { + alert('O telefone não pode estar vazio.'); return false; } @@ -228,11 +416,11 @@ function verificarSocio({bairro, cep, cidade, complemento, documento, email, est * Recebe como parâmetro um objeto do tipo Socio e preenche os campos do formulário automaticamente * @param {*} param0 */ -function formAutocomplete({bairro, cep, cidade, complemento, documento, email, estado, id, logradouro, nome, numeroEndereco, telefone}){ +function formAutocomplete({ bairro, cep, cidade, complemento, dataNascimento, documento, email, estado, id, logradouro, nome, numeroEndereco, telefone }) { //Definir elementos do HTML const nomeObject = document.getElementById('nome'); - //const dataNascimento = document.getElementById('data_nascimento'); + const dataNascimentoObject = document.getElementById('data_nascimento'); const emailObject = document.getElementById('email'); const telefoneObject = document.getElementById('telefone'); const cepObject = document.getElementById('cep'); @@ -245,6 +433,7 @@ function formAutocomplete({bairro, cep, cidade, complemento, documento, email, e //Atribuir valor aos campos nomeObject.value = nome; + dataNascimentoObject.value = dataNascimento; emailObject.value = email; telefoneObject.value = telefone; cepObject.value = cep; @@ -254,4 +443,23 @@ function formAutocomplete({bairro, cep, cidade, complemento, documento, email, e ufObject.value = estado; cidadeObject.value = cidade; complementoObject.value = complemento; +} + +function setLoader(btn) { + // Esconde o primeiro elemento filho (ícone) + btn.firstElementChild.style.display = "none"; + + // Remove o texto do botão sem remover os elementos filhos + btn.childNodes.forEach(node => { + if (node.nodeType === Node.TEXT_NODE) { + node.textContent = ''; + } + }); + + // Adiciona o loader se não houver outros elementos filhos além do ícone + if (btn.childElementCount == 1) { + var loader = document.createElement("DIV"); + loader.className = "loader"; + btn.appendChild(loader); + } } \ No newline at end of file diff --git a/html/apoio/service/PagarMeBoletoService.php b/html/apoio/service/PagarMeBoletoService.php index 24e50547..d2247adf 100755 --- a/html/apoio/service/PagarMeBoletoService.php +++ b/html/apoio/service/PagarMeBoletoService.php @@ -110,6 +110,9 @@ public function gerarBoleto(ContribuicaoLog $contribuicaoLog) $responseData = json_decode($response, true); $pdf_link = $responseData['charges'][0]['last_transaction']['pdf']; + //pegar o id do pedido na plataforma + $idPagarMe = $responseData['id']; + //armazena copía para segunda via $this->guardarSegundaVia($pdf_link, $contribuicaoLog); @@ -128,7 +131,7 @@ public function gerarBoleto(ContribuicaoLog $contribuicaoLog) } } - return true; + return $idPagarMe; } public function guardarSegundaVia($pdf_link, ContribuicaoLog $contribuicaoLog) { diff --git a/html/apoio/service/PagarMeCarneService.php b/html/apoio/service/PagarMeCarneService.php index 6f4be815..583e31a8 100755 --- a/html/apoio/service/PagarMeCarneService.php +++ b/html/apoio/service/PagarMeCarneService.php @@ -90,6 +90,7 @@ public function gerarCarne(ContribuicaoLogCollection $contribuicaoLogCollection) //Implementar requisição para API $pdf_links = []; + $codigosAPI = []; // Iniciar a requisição cURL $ch = curl_init(); @@ -123,6 +124,7 @@ public function gerarCarne(ContribuicaoLogCollection $contribuicaoLogCollection) if ($httpCode === 200 || $httpCode === 201) { $responseData = json_decode($response, true); $pdf_links[] = $responseData['charges'][0]['last_transaction']['pdf']; + $codigosAPI[] = $responseData['id']; } else { echo json_encode(['Erro' => 'A API retornou o código de status HTTP ' . $httpCode]); return false; @@ -150,7 +152,13 @@ public function gerarCarne(ContribuicaoLogCollection $contribuicaoLogCollection) return false; } - return $caminho; + //Pega os códigos retornados pela API e atribuí na propriedade codigo das contribuicoes de contribuicaoLogCollection + foreach($contribuicaoLogCollection as $index => $contribuicaoLog){ + $contribuicaoLog->setCodigo($codigosAPI[$index]); + } + + //Retorna o link e a coleção de contribuições + return ['link' => $caminho, 'contribuicoes' => $contribuicaoLogCollection]; } public function salvarTemp($pdf_links) diff --git a/html/apoio/tabelas.sql b/html/apoio/tabelas.sql index 0366179b..627c72c6 100755 --- a/html/apoio/tabelas.sql +++ b/html/apoio/tabelas.sql @@ -1,15 +1,24 @@ -- Posteriormente adicionar as tabelas desse arquivo ao banco de dados central do sistema CREATE TABLE IF NOT EXISTS `wegia`.`contribuicao_log` ( - `id` INT NULL DEFAULT NULL AUTO_INCREMENT, + `id` INT NOT NULL AUTO_INCREMENT, `id_socio` INT(11) NOT NULL, + `id_gateway` INT(11) NOT NULL, + `id_meio_pagamento` INT(11) NOT NULL, `codigo` VARCHAR(255) NOT NULL UNIQUE, `valor` DECIMAL(10,2) NOT NULL, `data_geracao` DATE NOT NULL, `data_vencimento` DATE NOT NULL, + `data_pagamento` DATE, `status_pagamento` BOOLEAN NOT NULL, PRIMARY KEY (`id`), CONSTRAINT `FK_id_socios` FOREIGN KEY (`id_socio`) - REFERENCES `wegia`.`socio` (`id_socio`) + REFERENCES `wegia`.`socio` (`id_socio`), + CONSTRAINT `FK_id_gateways` + FOREIGN KEY (`id_gateway`) + REFERENCES `wegia`.`contribuicao_gatewayPagamento` (`id`), + CONSTRAINT `FK_id_meio_pagamentos` + FOREIGN KEY (`id_meio_pagamento`) + REFERENCES `wegia`.`contribuicao_meioPagamento` (`id`) ) ENGINE = InnoDB; \ No newline at end of file diff --git a/html/apoio/view/boleto.php b/html/apoio/view/boleto.php index 081e4712..adea3f5a 100644 --- a/html/apoio/view/boleto.php +++ b/html/apoio/view/boleto.php @@ -12,34 +12,38 @@ - - -
- - -
- - - - - - - - +
+ + + +
+ + +
+ + + + + + + + +
+ @@ -48,8 +52,8 @@ - - + + \ No newline at end of file diff --git a/html/apoio/view/components/contribuicao_endereco.php b/html/apoio/view/components/contribuicao_endereco.php index 8e0e7598..f281eb70 100644 --- a/html/apoio/view/components/contribuicao_endereco.php +++ b/html/apoio/view/components/contribuicao_endereco.php @@ -65,7 +65,7 @@
- diff --git a/html/socio/sistema/controller/import_conteudo_psociogeracao.php b/html/socio/sistema/controller/import_conteudo_psociogeracao.php index dc78085d..1e69a54d 100755 --- a/html/socio/sistema/controller/import_conteudo_psociogeracao.php +++ b/html/socio/sistema/controller/import_conteudo_psociogeracao.php @@ -85,8 +85,12 @@
+ modify('+7 days')->format('Y-m-d'); + ?> - id="data_vencimento" name="data_vencimento" placeholder="Data vencimento" required> + id="data_vencimento" name="data_vencimento" placeholder="Data vencimento" value="" required>