Perse
Atualizado em
04/09/2024 16h37
perse.html
— 42 KB
Conteúdo do arquivo
<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Autorregularização Perse</title>
<!-- Google Tag Manager -->
<script type="text/javascript" async="" src="https://www.googletagmanager.com/gtag/js?id=G-WGZPDK4DH1&l=dataLayer&cx=c"></script>
<script async="" src="https://www.googletagmanager.com/gtm.js?id=GTM-NHZSKTD"></script>
<script type="text/javascript">(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
})(window,document,'script','dataLayer','GTM-NHZSKTD');
</script>
<!-- End Google Tag Manager -->
<!-- Fonte Rawline-->
<link rel="stylesheet"
href="https://cdngovbr-ds.estaleiro.serpro.gov.br/design-system/fonts/rawline/css/rawline.css" />
<!-- Fonte Raleway-->
<link rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Raleway:300,400,500,600,700,800,900&display=swap" />
<!-- Fontawesome-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/css/all.min.css" />
<!--CSS GOVBR-->
<link rel="stylesheet" href="./govbr/core.css" />
<!--JS GOVBR-->
<script src="./govbr/core.js"></script>
<!--COMPONENTES-->
<script src="./componentes/cabecalho/cabecalho.js"></script> <!--CABEÇALHO-->
<script src="./componentes/rodape/rodape.js"></script> <!--RODAPE-->
<script src="./componentes/br-textarea/br-textarea.js"></script> <!--TEXTAREA-->
<script src="./componentes/br-select/br-select.js"></script> <!--SELECT-->
<script src="./componentes/br-input/br-input.js"></script> <!--INPUT-->
<script src="./componentes/br-datepicker/br-datepicker.js"></script> <!--DATEPICKER-->
<script src="./componentes/custom-modal/custom-modal.js"></script> <!--CUSTOM MODAL-->
<!--UTILS-->
<script src="./bibliotecas/utils.js"></script> <!--DATEPICKER-->
<!--GET OPCOES SELECT-->
<script>
function getOpcoesTipoDeclaracao(){
return ['DCTF', 'Auto Infração', 'TDPF', 'Outro']
}
function getOpcoesCodReceita(){
return [
"966", "965", "963", "961", "220", "1113", "1324", "1330", "1347", "1409",
"2089", "2172", "2362", "2372", "2430", "2456", "2484", "2917", "2960",
"2973", "2986", "2999", "3020", "3074", "3084", "3087", "3090", "3252",
"3373", "3885", "5477", "5625", "5638", "5788", "5802", "5815", "5828",
"5856", "5937", "5993", "6012", "6094", "6138", "6324", "6337", "6378",
"6656", "6773", "6912", "7104", "7200", "7307", "7403", "8002", "8109",
"8128", "8143", "8156", "8169", "8305", "8361", "8401", "8408", "8430"
]
}
function getOpcoesUnidade(){
return ["unidade", "kg", "par", "garrafa", "litro", "metro"];
}
</script>
<!--HTML2CANVAS-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"
integrity="sha512-BNaRQnYJYiPSqHHDb58B0yaPfCu+Wgds8Gp/gU33kqBtgNS4tSPHuGibyoeqMV/TJlSKda6FXzoEyYGjTe+vXA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<!--JSPDF-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"
integrity="sha512-qZvrmS2ekKPF2mSznTQsxqPgnpkI4DNTlrdUmTzrDgektczlKNRRhy5X5AAOnx5S09ydFYWWNSfcEqDTTHgtNA=="
crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<style>
#custom-modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
overflow: auto;
}
#impressao-impedida {
display: none;
}
@media print{
body>*:not(#impressao-impedida) {
display: none;
}
#impressao-impedida {
display: block !important;
font-size: 2em;
}
}
body {
-webkit-user-select: none; /* Safari */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Standard */
}
</style>
</head>
<body>
<!--MAIN-->
<main class="template-base" id="main" style="min-height: 150vh !important;">
<!--CABECALHO-->
<section id="id-cabecalho">
<br-cabecalho></br-cabecalho>
</section>
<!--SECAO DEBITOS A REGULARIZAR-->
<section class="mb-5 toPdf" id="id-debitos-regularizar" name="Seção Débitos a Autorregularizar">
<div class="container-lg">
<div class="row">
<div class="col">
<div class="mb-5">
<h2>Débitos a Autorregularizar</h2>
</div>
<div class="br-table">
<table id="tb-debitos-regularizar" name="Tabela Débitos a Autorregularizar" class="mb-5" required>
<thead>
<tr>
<th class="text-up-01 p-2" style="width: 12%;">Tipo de declaração</th>
<th class="text-up-01 p-2" style="width: 12%;">Data da entrega</th>
<th class="text-up-01 p-2" style="width: 14%;">CPF/CNPJ do débito</th>
<th class="text-up-01 p-2" style="width: 14%;">Número do processo</th>
<th class="text-up-01 p-2" style="width: 9%;">Código Receita</th>
<th class="text-up-01 p-2" style="width: 10%;">Período Apuração</th>
<th class="text-up-01 p-2" style="width: 12%;">Vencimento do Tributo</th>
<th class="text-up-01 p-2" style="width: 12%;">Valor (R$)</th>
<th class="text-up-01 p-2 acoes" style="width: 5%;">Ações</th>
</tr>
</thead>
<tbody id="bd-debitos-regularizar"></tbody>
</table>
<!--BOTOES LIMPAR E INCLUIR NOVO DEBITO-->
<div id="btn-add-debitos-a-regularizar" class="botao">
<button onclick="excluirLinhasTabela(tbDebitosRegularizar)" class="br-button mr-3">Limpar</button>
<button onclick="incluirDebito()" class="br-button secondary mr-3">Incluir novo Débito</button>
</div>
</div>
</div>
</div>
</div>
</section>
<!--SECAO PF E BCN PROPRIOS-->
<section class="mb-5 toPdf" id="id-pf-bcn-proprios" name="Seção PF e BCN Próprios">
<div class="container-lg">
<div class="row">
<div class="col">
<div class="mb-5">
<h2>Créditos de Prejuízo Fiscal (PF) e Base de Cálculo Negativa da CSLL (BCN)</h2>
<h3 class="text-bold">PRÓPRIOS</h3>
<h5>Exclusivo para Pessoa Jurídica</h5>
<h5>Nos termos da legislação, o uso dos créditos de PF/BCN é limitado a 50% da dívida consolidada</h5>
</div>
<div class="br-table">
<table id="id-tb-pf-bcn" class="mb-5" name="Tabela PF e BCN Próprios" data-opcional="opcional">
<thead>
<tr>
<th class="text-up-01 p-2 col-3">Tipo</th>
<th class="text-up-01 p-2 col-2">Montante</th>
<th class="text-up-01 p-2 col-2">Alíquota</th>
<th class="text-up-01 p-2 col-2">Valor</th>
<th class="text-up-01 p-2 col-2">Data entrega ECF</th>
</tr>
</thead>
<tbody id="id-bd-pf-bcn">
<tr>
<td>
<br-input inputId="id-tipo-pf" inputClass="border-gray-90 text-weight-bold" eName="Tipo de crédito" initValue="PF" isDisabled></br-input>
</td>
<td class="p-2">
<br-input inputId="id-montante-pf" eName="Montante Prejuío Fiscal" onchange="validarValor"></br-input>
</td>
<td>
<br-input inputId="id-aliquota-pf" inputClass="border-gray-90 text-weight-bold" eName="Alíquota (PF)" initValue="25%" isDisabled></br-input>
</td>
<td class="p-2">
<br-input inputId="id-valor-pf" eName="Valor Prejuízo Fiscal" onchange="validarValor"></br-input>
</td>
<td class="p-2">
<!--DATA ENTREGA ECF-->
<br-datepicker eName="Data Entrega ECF PF" maxdate='18/11/2024'></br-datepicker>
</td>
</tr>
<tr>
<td>
<br-input inputId="id-tipo-bcn" inputClass="border-gray-90 text-weight-bold" eName="Tipo de crédito" initValue="BCN da CSLL" isDisabled></br-input>
</td>
<td class="p-2">
<br-input inputId="id-montante-bcn" eName="Montante BCN CSLL" onchange="validarValor"></br-input>
</td>
<td>
<br-input inputId="id-aliquota-bcn" inputClass="border-gray-90 text-weight-bold" eName="Alíquota (BCN)" initValue="9%" isDisabled></br-input>
</td>
<td class="p-2">
<br-input inputId="id-valor-bcn" eName="Valor BCN CSLL" onchange="validarValor"></br-input>
</td>
<td class="p-2">
<!--DATA ENTREGA ECF-->
<br-datepicker eName="Data Entrega ECF BCN" maxdate='18/11/2024'></br-datepicker>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</section>
<!--SECAO PF E BCN TERCEIROS-->
<section class="mb-5 toPdf" id="id-pf-bcn-terceiros" name="Seção PF e BCN Terceiros">
<div class="container-lg">
<div class="row">
<div class="col">
<div class="mb-5">
<h2>Créditos de Prejuízo Fiscal (PF) e Base de Cálculo Negativa da CSLL (BCN)</h2>
<h3 class="text-bold">TERCEIROS</h3>
<h5>Exclusivo para Pessoa Jurídica</h5>
<h5>Nos termos da legislação, o uso dos créditos de PF/BCN é limitado a 50% da dívida consolidada</h5>
</div>
<div class="br-table">
<table id="tb-pf-bcn-terceiros" name="Tabela PF e BCN Terceiros" class="mb-5">
<thead>
<tr>
<th class="text-up-01 p-2 col-2">CNPJ</th>
<th class="text-up-01 p-2 col-2">Tipo</th>
<th class="text-up-01 p-2 col-2">Montante</th>
<th class="text-up-01 p-2 col-1">Alíquota</th>
<th class="text-up-01 p-2 col-2">Valor</th>
<th class="text-up-01 p-2 col-2">Data entrega ECF</th>
<th class="text-up-01 p-2 col-1 acoes">Ações</th>
</tr>
</thead>
<tbody id="bd-pf-bcn-terceiros"></tbody>
</table>
<!--BOTOES LIMPAR E INCLUIR NOVO CRÉDITO-->
<div id="btn-add-pf-bcn-terceiros" class="botao">
<button onclick="excluirLinhasTabela(tbPfBcnTerceiros)" class="br-button mr-3">Limpar</button>
<button onclick="incluirCreditoTerceiros('PF')" class="br-button secondary mr-3">Incluir novo Crédito - PF</button>
<button onclick="incluirCreditoTerceiros('BCN')" class="br-button secondary mr-3">Incluir novo Crédito - BCN</button>
</div>
</div>
</div>
</div>
</div>
</section>
<!--SECAO BOTAO GERAR DOCUMENTO-->
<section class="mb-5" id="id-gerar-documento">
<div class="container-fluid">
<div class="row">
<div class="col">
<div class="text-center my-3">
<button onclick="gerarPDF()" class="br-button primary">Gerar Documento</button>
</div>
</div>
</div>
</div>
</section>
</main>
<!-- MENSAGEM PADRÃO DE IMPRESSÃO -->
<section>
<div id="impressao-impedida" class="text-center">Utilize o botão Gerar Documento</div>
</section>
<!--MODAL GOVBR-->
<section id="id-modal">
<custom-modal></custom-modal>
</section>
<!--CONFIRMATION MODAL-->
<div id="confirmation-modal" class="div br-modal medium align-self-center d-none" aria-modal="true" role="dialog" aria-labelledby="modal-title" style="position: absolute; top:40%;">
<div class="br-modal-header">
<div class="modal-title" id="modal-title">ATENÇÃO</div>
<button class="br-button close circle" type="button" data-dismiss="br-modal" aria-label="Fechar" id="btn-close"><i class="fas fa-times" aria-hidden="true"></i>
</button>
</div>
<div class="br-modal-body" id="modal-message">
<!-- <p></p> -->
</div>
<div class="br-modal-footer justify-content-end">
<button class="br-button primary ml-2" type="button" id="btn-entendi">Entendi</button>
<button class="br-button primary ml-2" type="button" id="btn-sim">Sim</button>
<button class="br-button primary ml-2" type="button" id="btn-nao">Não</button>
</div>
</div>
<!--RODAPE-->
<section id="id-rodape">
<br-rodape></br-rodape>
</section>
<!--COOKIE BAR-->
<section id="id-cookiebar">
<div class="br-cookiebar default" tabindex="-1"></div>
</section>
<!-- JAVASCRIPT PARA CUSTOM-MODAL -->
<script>
const modalComponent = document.querySelector('custom-modal');
function showAlertModal(mensagem) {
modalComponent.showModal(mensagem);
}
// ESCONDE MODAL
function closeModal() {
modalComponent.classList.add('d-none');
let buttons = document.querySelectorAll('button:not(#custom-modal button), input');
buttons.forEach(function(button) {
button.disabled = false;
});
}
</script>
<script>
////////// VARIÁVEIS //////////
let tbDebitosRegularizar = document.querySelector('#tb-debitos-regularizar');
let bdDebitosRegularizar = document.querySelector('#bd-debitos-regularizar');
let tbPfBcnTerceiros = document.querySelector('#tb-pf-bcn-terceiros');
let bdPfBcnTerceiros = document.querySelector('#bd-pf-bcn-terceiros');
let secoesToPdf = document.querySelectorAll('.toPdf');
let secaoConteudoPdf = document.querySelector('#id-conteudo-pdf');
// INCLUIR DEBTIO NA TABELA DEBITOS A REGULARIZAR
function incluirDebito() {
var novaLinha = bdDebitosRegularizar.insertRow(-1);
for (var i = 0; i < 9; i++) {
var novaCelula = novaLinha.insertCell(i);
novaCelula.classList.add('p-2');
// TIPO DECLARAÇÃO (select)
if (i == 0) {
let tipoDeclaracao = document.createElement('br-select-component');
tipoDeclaracao.setAttribute('opcoes', 'getOpcoesTipoDeclaracao');
tipoDeclaracao.setAttribute('eName', 'Tipo de declaração');
tipoDeclaracao.setAttribute('inputClass', 'text-sm-down-01');
tipoDeclaracao.setAttribute('required', 'required');
novaCelula.appendChild(tipoDeclaracao);
}
// DATA ENTREGA (calendario)
if (i == 1) {
let dataEntrega = document.createElement('br-datepicker');
dataEntrega.setAttribute('eName', 'Data da entrega');
dataEntrega.setAttribute('inputClass', 'text-sm-down-01');
dataEntrega.setAttribute('required', 'required');
novaCelula.appendChild(dataEntrega);
}
// CPF/CNPJ DEBITO (input)
if (i == 2) {
let cnpjCpf = document.createElement('br-input');
cnpjCpf.setAttribute('eName', 'CNPJ/CPF');
cnpjCpf.setAttribute('inputClass', 'text-sm-down-01');
cnpjCpf.setAttribute('required', 'required');
cnpjCpf.setAttribute('onchange', 'validarCNPJCPF');
novaCelula.appendChild(cnpjCpf);
}
// NÚMERO DO PROCESSO (input)
if (i == 3) {
let nProcesso = document.createElement('br-input');
nProcesso.setAttribute('eName', 'nProcesso');
nProcesso.setAttribute('inputClass', 'text-sm-down-01');
nProcesso.setAttribute('onchange', 'validarProcesso');
novaCelula.appendChild(nProcesso);
}
// CODIGO DE RECEITA (select)
if (i == 4) {
let codReceita = document.createElement('br-select-component');
codReceita.setAttribute('opcoes', 'getOpcoesCodReceita');
codReceita.setAttribute('eName', 'Código de receita');
codReceita.setAttribute('inputClass', 'text-sm-down-01');
codReceita.setAttribute('required', 'required');
novaCelula.appendChild(codReceita);
}
// PERIODO DE APURACAO (calendario)
if (i == 5) {
let periodoApuracao = document.createElement('br-datepicker');
periodoApuracao.setAttribute('eName', 'Período apuração');
periodoApuracao.setAttribute('inputClass', 'text-sm-down-01');
periodoApuracao.setAttribute('required', 'required');
periodoApuracao.setAttribute('mindate', '01/03/2022');
periodoApuracao.setAttribute('maxdate', '31/05/2024');
novaCelula.appendChild(periodoApuracao);
}
// VENCIMENTO TRIBUTO (calendario)
if (i == 6) {
let vencimentoTributo = document.createElement('br-datepicker');
vencimentoTributo.setAttribute('eName', 'Vencimento do tributo');
vencimentoTributo.setAttribute('inputClass', 'text-sm-down-01');
vencimentoTributo.setAttribute('required', 'required');
vencimentoTributo.setAttribute('mindate', '01/03/2022');
vencimentoTributo.setAttribute('maxdate', '30/06/2024');
novaCelula.appendChild(vencimentoTributo);
}
// VALOR (input)
if (i == 7) {
let valor = document.createElement('br-input');
valor.setAttribute('eName', 'Valor');
valor.setAttribute('inputClass', 'text-sm-down-01');
valor.setAttribute('required', 'required');
valor.setAttribute('onchange', 'validarValor');
novaCelula.appendChild(valor);
}
// AÇÕES (botão)
if (i == 8){
novaCelula.classList.add('acoes');
let btnExcluir = document.createElement('button');
let iconeLixeira = document.createElement('i');
btnExcluir.classList.add('br-button');
iconeLixeira.classList.add('fa', 'fa-trash-alt');
btnExcluir.appendChild(iconeLixeira);
novaCelula.appendChild(btnExcluir);
btnExcluir.addEventListener('click', function () {
excluirLinha(this);
});
}
}
}
// ADICIONA LINHA NA TABELA CRÉDITOS PF/BCN TERCEIROS
function incluirCreditoTerceiros(tipoCredito){
if(tipoCredito != "PF" && tipoCredito !="BCN"){
tipoCredito = "PF";
};
var novaLinha = bdPfBcnTerceiros.insertRow(-1);
for (var i = 0; i < 7; i++) {
var novaCelula = novaLinha.insertCell(i);
novaCelula.classList.add('p-2');
// CNPJ CREDITO TERCEIROS (input)
if (i == 0) {
let cnpj = document.createElement('br-input');
cnpj.setAttribute('eName', 'CNPJ');
cnpj.setAttribute('required', 'required');
cnpj.setAttribute('onchange', 'validarCNPJ');
novaCelula.appendChild(cnpj);
}
// TIPO CREDITO (input disabled) - depende de qual botão clicado (tipoCredito)
if (i == 1) {
let tipo = document.createElement('br-input');
tipo.setAttribute('eName', 'Tipo de crédito');
tipo.setAttribute('inputClass', 'border-gray-90 text-weight-bold');
tipo.setAttribute('required', 'required');
tipo.setAttribute('isDisabled', 'disabled');
if (tipoCredito == "BCN"){
tipo.setAttribute('initValue', 'BCN da CSLL');
}else{
tipo.setAttribute('initValue', 'PF');
}
novaCelula.appendChild(tipo);
}
// MONTANTE (input)
if (i == 2) {
let montante = document.createElement('br-input');
montante.setAttribute('eName', 'Montante');
montante.setAttribute('required', 'required');
montante.setAttribute('onchange', 'validarValor');
novaCelula.appendChild(montante);
}
// ALIQUOTA (input disabled) - depende de qual botão clicado (tipoCredito)
if (i == 3) {
let aliquota = document.createElement('br-input');
aliquota.setAttribute('eName', 'Alíquota');
aliquota.setAttribute('inputClass', 'border-gray-90 text-weight-bold');
aliquota.setAttribute('required', 'required');
aliquota.setAttribute('isDisabled', 'disabled');
if (tipoCredito == "BCN"){
aliquota.setAttribute('initValue', '9%');
}else{
aliquota.setAttribute('initValue', '25%');
}
novaCelula.appendChild(aliquota);
}
// VALOR (input)
if (i == 4) {
let valor = document.createElement('br-input');
valor.setAttribute('eName', 'Valor');
valor.setAttribute('required', 'required');
valor.setAttribute('onchange', 'validarValor');
novaCelula.appendChild(valor);
}
// DATA ENTREGA ECF (calendario)
if (i == 5) {
let dataEntregaECF = document.createElement('br-datepicker');
dataEntregaECF.setAttribute('eName', 'Data entrega ECF');
dataEntregaECF.setAttribute('required', 'required');
dataEntregaECF.setAttribute('maxdate', '18/11/2024');
novaCelula.appendChild(dataEntregaECF);
}
// AÇÕES (botão)
if (i == 6){
novaCelula.classList.add('acoes');
let btnExcluir = document.createElement('button');
let iconeLixeira = document.createElement('i');
btnExcluir.classList.add('br-button');
iconeLixeira.classList.add('fa', 'fa-trash-alt');
btnExcluir.appendChild(iconeLixeira);
novaCelula.appendChild(btnExcluir);
btnExcluir.addEventListener('click', function () {
excluirLinha(this);
});
}
}
}
// EXCLUI TODAS AS LINHAS DE UMA TABELA - BOTAO LIMPAR
async function excluirLinhasTabela(tabela) {
// se a tabela tiver apenas cabeçalho, retorna
if (tabela.rows.length < 2) return;
if (! await showConfirmationModal("Tem certeza que deseja apagar todos dados dessa tabela?")) {
return;
}
var linhas = tabela.rows;
// Começa do final para evitar problemas com o índice mudando durante a remoção
for (var i = linhas.length - 1; i > 0; i--) {
tabela.deleteRow(i);
}
}
// MODAL DE CONFIRMACAO
function showConfirmationModal(mensagem) {
return new Promise((resolve) => {
const modal = document.getElementById('confirmation-modal');
const modalMessage = modal.querySelector('#modal-message');
const btnEntendi = modal.querySelector('#btn-entendi');
const btnClose = modal.querySelector('#btn-close');
const btnSim = modal.querySelector('#btn-sim');
const btnNao = modal.querySelector('#btn-nao');
btnEntendi.classList.add('d-none');
modalMessage.classList.add('text-up-01');
modal.style.position = 'fixed';
modal.style.top = "50%";
modal.style.left = "50%";
modal.style.transform = "translate(-50%, -50%)";
modal.style.zIndex = '1000';
modalMessage.innerHTML = mensagem;
// Adicionando event listeners para os botões
btnSim.addEventListener('click', () => {
resolve(true);
closeConfirmationModal();
});
btnNao.addEventListener('click', () => {
resolve(false);
closeConfirmationModal();
});
btnClose.addEventListener('click', () => {
resolve(false);
closeConfirmationModal();
});
modal.classList.remove('d-none');
});
}
// ESCONDE MODAL
function closeConfirmationModal() {
// remove d-none dos botões para próximo modal
const btnEntendi = document.querySelector('#btn-entendi');
const btnSim = document.getElementById('btn-sim');
const btnNao = document.getElementById('btn-nao');
btnEntendi.classList.remove('d-none');
btnSim.classList.remove('d-none');
btnNao.classList.remove('d-none');
const modal = document.getElementById('confirmation-modal');
modal.classList.add('d-none');
}
// VALIDAÇÃO DOS ELEMENTOS E CRIAÇÃO DO PDF
// PREPARA CONTEUDO PARA PDF
function prepararPdf(secoes){
let continuar = true; // Variável de controle
for (let secao of secoes) {
if(!validarTabelasOpcionais(secao.id)){
let tabelaNome = secao.querySelector('table[data-opcional="opcional"]').getAttribute('name');
showAlertModal(`A <span class="text-bold">${tabelaNome}</span> possui linhas incompletas`)
continuar = false;
break
}
if(!validarTabelasObrigatorias(secao.id)){
let tabelaNome = secao.querySelector('table[required]').getAttribute('name');
showAlertModal(`A <span class="text-bold">${tabelaNome}</span> é de preenchimento obrigatório`)
continuar = false;
break
}
if(!validarCamposRequiredNaSecao(secao.id)){
showAlertModal('Existem campos obrigatórios não preenchidos')
continuar = false;
break
}
}
if (!continuar) return false;
return true
}
// VALIDAR TABELA OPCIONAL
function validarTabelasOpcionais(secaoId) {
const secao = document.getElementById(secaoId);
let continuar = true; // Variável de controle
if (!secao) {
console.error(`Seção com ID "${secaoId}" não encontrada.`);
return;
}
const tabela = secao.querySelector('table[data-opcional="opcional"]');
if (tabela) {
const linhas = tabela.querySelectorAll('tbody tr');
if (linhas) {
for (let linha of linhas) {
const inputs = linha.querySelectorAll('input:not([disabled])');
let algumPreenchido = false;
let todosPreenchidos = true;
// Verificar se algum campo na linha está preenchido
for (let input of inputs) {
if (input.value.trim() !== '') {
algumPreenchido = true;
} else {
todosPreenchidos = false;
}
}
// Se algum campo está preenchido, todos devem estar preenchidos
if (algumPreenchido && !todosPreenchidos) {
showAlertModal('Se um campo estiver preenchido, todos os campos da linha devem ser preenchidos.');
continuar = false;
break;
}
}
}
}
return continuar;
}
// FUNÇÃO QUE VALIDA DADOS E GERA PDF
async function gerarPDF(){
if (!await showConfirmationModal(
"Após clicar em 'Sim' será disponibilizado para download um arquivo extensão .PDF, \
que deverá ser obrigatoriamente anexado ao Requerimento Web. <br><br>Em seguida, \
<b>os dados inseridos nessa página serão apagados.</b> <br><br>Tem certeza que deseja continuar?"))
return;
if (!prepararPdf(secoesToPdf)) return;
//AJUSTA TEXTAREAS PARA PDF
ajustarTextareas();
html2canvas(document.querySelector('body')).then(canvas => {
const imgData = canvas.toDataURL('image/jpeg', 0.7);
const pdf = new jspdf.jsPDF('landscape');
// Define as dimensões da página
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
// Dimensões da imagem
const imgWidth = canvas.width;
const imgHeight = canvas.height;
// Proporção de redimensionamento da imagem
const ratio = pageWidth / imgWidth;
const scaledHeight = imgHeight * ratio;
// Número total de páginas necessárias
let totalPages = Math.ceil(scaledHeight / pageHeight);
for (let i = 0; i < totalPages; i++) {
const position = -(pageHeight * i);
// Adiciona a imagem ao PDF, cortando a parte visível da página
pdf.addImage(imgData, 'JPEG', 0, position, pageWidth, scaledHeight);
// Adiciona uma nova página se não for a última
if (i < totalPages - 1) {
pdf.addPage();
}
}
let json = gerarJSON(secoesToPdf);
// Define metadados do PDF
pdf.setProperties({
keywords: json,
});
pdf.save("autorregularizacaoPerse.pdf");
});
// Após o download do PDF, recarrega a página.
setTimeout(function() {
location.reload();
}, 5000); // Tempo em milissegundos (5 segundos)
// showAlertModal('PDF gerado e salvo com sucesso!')
}
// EXTRAI VALORES DOS ELEMENTOS DE FORMULARIO
function extrairValores(elemento){
let chaveSecao = {};
// capturar os componentes de cada elemento (exemplo: secao, linha de tabela, div)
let brInputs = elemento.querySelectorAll('br-input');
let brTextareas = elemento.querySelectorAll('br-textarea');
let brDatepickers = elemento.querySelectorAll('br-datepicker');
// let brSelects = elemento.querySelectorAll('br-select');
let brSelectComponents = elemento.querySelectorAll('br-select-component');
let selectUF = elemento.querySelector('select-ufs');
let selectMunicipio = elemento.querySelector('select-municipio');
if (selectUF){
chaveSecao['Estado de destino'] = selectUF.querySelector (".br-item.selected>.br-radio>label").textContent;
}
if (selectMunicipio){
chaveSecao['Municipio de destino'] = selectMunicipio.querySelector (".br-item.selected>.br-radio>label").textContent;
}
brSelectComponents.forEach(brSelectComponent => {
const name = brSelectComponent.querySelector('input').name;
const value = brSelectComponent.querySelector('.br-item.selected').querySelector('input').value;
chaveSecao[name] = value;
});
brInputs.forEach(brInput => {
const name = brInput.querySelector('input').getAttribute('name');
const value = brInput.querySelector('input').value;
chaveSecao[name] = value;
});
brTextareas.forEach(brTextarea => {
const name = brTextarea.querySelector('textarea').getAttribute('name');
const value = brTextarea.querySelector('textarea').value;
chaveSecao[name] = value;
});
brDatepickers.forEach(brDatepicker => {
const name = brDatepicker.querySelector('input').getAttribute('name');
const value = brDatepicker.querySelector('input').value;
chaveSecao[name] = value;
});
return chaveSecao;
}
// GERA JSON PARA INCLUIR NOS METADADOS DO PDF
function gerarJSON(secoes) {
const jsonData = {};
const dataAtual = new Date();
const dia = dataAtual.getDate();
const mes = dataAtual.getMonth() + 1; // Meses são indexados de 0 (Janeiro) a 11 (Dezembro), por isso adicionamos 1
const ano = dataAtual.getFullYear();
const dataFormatada = `${String(dia).padStart(2, '0')}/${String(mes).padStart(2, '0')}/${ano}`;
jsonData["versao"]= "1.0";
jsonData["data-de-criacao"]= dataFormatada;
for (let secao of secoes) {
let tabela = secao.querySelector('table');
// verificar se tem tabela na secao - criar objetos para cada linha da tabela
// se não tiver, cada name pode ser chave
if (!tabela){
jsonData[secao.getAttribute('name')] = extrairValores(secao);
}else{ // tem tabela
let secaoTabela = [];
let linhas = tabela.querySelectorAll('tbody tr');
for (let linha of linhas){
secaoTabela.push(extrairValores(linha));
}
jsonData['Tabela - ' + secao.getAttribute('name')] = secaoTabela;
}
}
return JSON.stringify(jsonData, null, 2)
}
// Desabilitar atalhos de teclado comuns para impressão
document.addEventListener('keydown', function(e) {
if ((e.ctrlKey || e.metaKey) && (e.key === 'p' || e.key === 'P')) {
e.preventDefault();
e.stopPropagation();
showAlertModal("Utilize o botão Gerar Documento");
}
});
</script>
</body>
</html>