D7net
Home
Console
Upload
information
Create File
Create Folder
About
Tools
:
/
var
/
www
/
html
/
novonote
/
adm
/
app
/
gre
/
Views
/
Orcamento
/
Filename :
VieCadastrarOrcamento_1.php
back
Copy
<?php $categoria = $_SESSION['form']['condicoes'] ?? ''; ?> <?php if (isset($_SESSION['form'])) { $valorForm = $_SESSION['form']; } //if (isset($this->Dados['select']['dadosTab'])) { //var_dump( $this->Dados['select']['dadosTab']); //} ?> <style> .btn:hover { color: white; /* Altera o texto para branco no hover */ } .modal-dialog { max-width: 80vw !important;/* Ajusta a largura */ height: 70vh !important; /* Ajusta a altura */ } .modal-content { height: 100%; /* Garante que o conteúdo ocupe toda a altura */ } .close { background-color: #ffffff !important; /* Fundo branco */ border: none !important; /* Remove qualquer borda */ opacity: 1 !important; /* Garante que esteja visível */ width: 40px; /* Aumenta a largura */ height: 40px; /* Aumenta a altura */ font-size: 36px; /* Ajusta o tamanho do ícone */ align-items: center; table { width: 100%; border-collapse: collapse !important; border: 2px solid black !important; } th, td { border: 2px solid black !important; padding: 8px; text-align: left; background-color: white; } th { text-align: center !important; } label { display: inline-block !important; /* ou inline, se preferir */ width: auto !important; white-space: nowrap !important; /* evita quebrar em várias linhas */ } #tabelaResultados th, #tabelaResultados td { padding: 4px !important; border: 1px solid #ccc; font-size: 0.8em !important; line-height: 1.1 !important; } #tabelaResultados thead tr { background: #f0f0f0; </style> <body> <div class="container-fluid px-0"> <div class="content"> <div class="list-group-item"> <div class="d-flex align-items-center justify-content-between"> <div class="mr-auto p-2"> <h2 class="display-4 titulo">Gerar Proposta</h2> </div> <div class="p-2"> <?php if ($this->Dados['botao']['lis_orcamento']) { ?> <a href="<?php echo URLADM . 'orcamento/listar'; ?>" class="btn btn-outline-info btn-sm">Listar</a> <?php } ?> </div> </div> <hr> <?php if (isset($_SESSION['msg'])) { echo $_SESSION['msg']; unset($_SESSION['msg']); } ?> <form id="form_orcamento" method="POST" action="" enctype="multipart/form-data"> <ul class="nav nav-tabs mt-4" id="abasItens" role="tablist"> <li class="nav-item" role="presentation"> <button class="nav-link active" id="aba-form-tab" data-bs-toggle="tab" data-bs-target="#aba-form" type="button" role="tab">Proposta</button> </li> <li class="nav-item" role="presentation"> <button class="nav-link" id="aba-itens-tab" data-bs-toggle="tab" data-bs-target="#aba-itens" type="button" role="tab">Itens Incluídos</button> </li> </ul> <!-- Para prazo 1 --> <input type="hidden" name="valorAntivirus1" id="valorAntivirus1"> <input type="hidden" name="valorOffice1" id="valorOffice1"> <input type="hidden" name="valorDepreciacao1" id="valorDepreciacao1"> <input type="hidden" name="valorManutencao1" id="valorManutencao1"> <input type="hidden" name="valorCiclo1" id="valorCiclo1"> <input type="hidden" name="precoMensal1" id="precoMensal1"> <input type="hidden" name="lucroLiquido1" id="lucroLiquido1"> <!-- Para prazo 2 --> <input type="hidden" name="valorAntivirus2" id="valorAntivirus2"> <input type="hidden" name="valorOffice2" id="valorOffice2"> <input type="hidden" name="valorDepreciacao2" id="valorDepreciacao2"> <input type="hidden" name="valorManutencao2" id="valorManutencao2"> <input type="hidden" name="valorCiclo2" id="valorCiclo2"> <input type="hidden" name="precoMensal2" id="precoMensal2"> <input type="hidden" name="lucroLiquido2" id="lucroLiquido2"> <!-- Para prazo 3 --> <input type="hidden" name="valorAntivirus3" id="valorAntivirus3"> <input type="hidden" name="valorOffice3" id="valorOffice3"> <input type="hidden" name="valorDepreciacao3" id="valorDepreciacao3"> <input type="hidden" name="valorManutencao3" id="valorManutencao3"> <input type="hidden" name="valorCiclo3" id="valorCiclo3"> <input type="hidden" name="precoMensal3" id="precoMensal3"> <input type="hidden" name="lucroLiquido3" id="lucroLiquido3"> <input type="hidden" name="prazo1" id="prazo1"> <input type="hidden" name="prazo2" id="prazo2"> <input type="hidden" name="prazo3" id="prazo3"> <input type="hidden" name="temoffice" id="temoffice" value="N"> <input type="hidden" name="temantivirus" id="temantivirus" value="N"> <input type="hidden" name="urladm" id="urladm" value="<?php echo URLADM ?>"> <input type="hidden" name="cep1" id="cep1" value="02124002"> <input type="hidden" name="perc_frete" id="perc_frete" value="<?php echo $this->Dados['select']['param'][0]['perc_frete'] ?>"> <input type="hidden" name="perc_impostos" id="perc_impostos" value="<?php echo $this->Dados['select']['param'][0]['perc_impostos'] ?>"> <input type="hidden" name="valor_office" id="valor_office" value="<?php echo $this->Dados['select']['param'][0]['valor_office'] ?>"> <input type="hidden" name="qtde_licenca_office" id="qtde_licenca_office" value="<?php echo $this->Dados['select']['param'][0]['qtde_licenca_office'] ?>"> <input type="hidden" name="valor_antivirus" id="valor_antivirus" value="<?php echo $this->Dados['select']['param'][0]['valor_antivirus'] ?>"> <input type="hidden" name="qtde_licenca_antivirus" id="qtde_licenca_antivirus" value="<?php echo $this->Dados['select']['param'][0]['qtde_licenca_antivirus'] ?>"> <div class="tab-content border border-top-0 p-3" id="conteudoAbas"> <div class="tab-pane fade show active" id="aba-form" role="tabpanel"> <div class="row gy-3"> <div class="col-12"> <div class="d-flex flex-wrap align-items-center gap-3"> <!-- Cliente --> <div class="d-flex align-items-center"> <label class="form-label me-2" for="cliente_input"> <span class="text-danger">*</span>Cliente: </label> <input list="clientes" id="cliente_input" class="form-control" style="width: 250px;" placeholder="Digite ou selecione um cliente" required value="<?= isset($valorForm['nome_cliente']) ? htmlspecialchars($valorForm['nome_cliente']) : '' ?>"> <?php if (empty($valorForm['nome_cliente'])): ?> <datalist id="clientes"> <?php foreach ($this->Dados['select']['cliente'] as $cliente): ?> <option value="<?= htmlspecialchars($cliente['nome_cliente']) ?>" data-contato="<?= htmlspecialchars($cliente['contato_cliente']) ?>" data-celular="<?= htmlspecialchars($cliente['celular_cliente']) ?>" data-email="<?= htmlspecialchars($cliente['email_cliente']) ?>"> </option> <?php endforeach; ?> </datalist> <?php endif; ?> <button type="button" class="btn btn-outline-primary btn-sm ms-2" id="btnToggleCampoCliente" title="Novo"> <i class="fas fa-plus" title="Informar Novo Cliente"></i> </button> </div> <!-- Contato --> <div class="d-flex align-items-center"> <label class="form-label me-2"><span class="text-danger">*</span>Contato:</label> <input type="text" class="form-control" name="contato" id="contato" style="width: 150px;" value="<?= isset($valorForm['contato']) ? htmlspecialchars($valorForm['contato']) : '' ?>" <?= !empty($valorForm['contato']) ? 'readonly' : '' ?>> <input type="text" name="novo_contato" id="novo_contato" class="form-control placeholder-verde d-none ms-2" placeholder="Digite novo Contato" style="width: 150px;"> </div> <!-- Celular --> <div class="d-flex align-items-center"> <label class="form-label me-2"><span class="text-danger">*</span>Celular:</label> <input type="text" class="form-control" name="celular" id="cel" style="width: 150px;" value="<?= isset($valorForm['celular']) ? htmlspecialchars($valorForm['celular']) : '' ?>" <?= !empty($valorForm['celular']) ? 'readonly' : '' ?>> <input type="text" name="novo_celular" id="cel2" class="form-control placeholder-verde d-none ms-2" placeholder="Digite novo Celular" style="width: 150px;"> </div> </div> </div> </div> <div class="row gy-3"> <div class="col-12"> <div class="d-flex flex-wrap align-items-center gap-3"> <div class="d-flex align-items-center"> <label class="form-label me-2"><span class="text-danger">*</span>eMail:</label> <input type="email" class="form-control" name="email" id="email" style="width: 200px;" value="<?= isset($valorForm['email']) ? htmlspecialchars($valorForm['email']) : '' ?>" <?= !empty($valorForm['email']) ? 'readonly' : '' ?>> <input type="email" name="novo_email" id="novo_email" class="form-control placeholder-verde d-none ms-2" placeholder="Digite novo email" style="width: 200px;"> </div> <!-- Validade da Proposta --> <div class="d-flex align-items-center"> <label class="form-label me-2"><span class="text-danger">*</span>Validade da Proposta:</label> <input type="date" class="form-control w-auto" name="data_validade" id="data_validade" value="<?= isset($valorForm['data_validade']) ? htmlspecialchars($valorForm['data_validade']) : '' ?>" <?= !empty($valorForm['data_validade']) ? 'readonly' : '' ?>> </div> <!-- Prazo do Contrato --> <div class="d-flex align-items-center"> <label class="form-label me-2"><span class="text-danger">*</span>Prazo do Contrato:</label> <?php $selectReadonly = false; foreach ($this->Dados['select']['prazo'] as $prazo) { extract($prazo); if (isset($valorForm) && $valorForm['gre_prazo_id'] == $id_prazo) { $selectReadonly = true; break; } } ?> <select name="gre_prazo_id" id="gre_prazo_id" class="form-select w-auto" required style="width: 150px !important;" <?= $selectReadonly ? 'disabled' : '' ?>> <?php if (!isset($valorForm)) { echo "<option value=''>Selecione</option>"; } foreach ($this->Dados['select']['prazo'] as $prazo) { extract($prazo); $selected = (isset($valorForm) && $valorForm['gre_prazo_id'] == $id_prazo) ? 'selected' : ''; echo "<option value='$id_prazo' $selected>$nome_prazo</option>"; } ?> </select> </div> </div> </div> </div> <!-- até aqui alterado --> <div class="row gy-3"> <div class="d-flex flex-wrap gap-3 align-items-center"> <div class="d-flex align-items-center"> <label class="me-1"><span class="text-danger">*</span>Categoria:</label> <select name="gre_cat_id" id="gre_cat_id" class="form-control" required onchange="pegaMarca(this.value)" style="width: 150px !important;"> <option value="">Selecione</option> <?php foreach ($this->Dados['select']['cat'] as $cat) { extract($cat); echo "<option value='$id_cat' data-depr='$perc_depr' data-manut='$perc_manutencao' data-margem='$perc_margem' data-office='$office' data-antivirus='$antivirus'>$nome_cat</option>"; } ?> </select> </div> <div class="d-flex flex-wrap gap-3 align-items-center"> <div class="d-flex align-items-center"> <label class="me-2">Depreciação:</label> <input type="text" name="perc_depreciacao" id="perc_depreciacao" class="form-control" style="width: 100px;" requires readonly> </div> <div class="d-flex align-items-center"> <label class="me-2">Manutenção:</label> <input type="text" name="perc_manutencao" id="perc_manutencao" class="form-control" style="width: 100px;" requires readonly> </div> <div class="d-flex align-items-center"> <label class="me-2">Margem</label> <input type="text" name="perc_margem" id="perc_margem" class="form-control" style="width: 75px;" requires readonly> </div> </div> </div> </div> <div class="row gy-3"> <div class="d-flex flex-wrap gap-3 align-items-center"> <div id="offi"> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Incluir Office ?:</label> <select name="office" id="office" class="form-control" required style="width: 100px !important;"> <option value="">Selecione</option> <option value="S">Sim</option> <option value="N">Não</option> </select> </div> </div> <div id="viri"> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Incluir Antivírus?:</label> <select name="antivirus" id="antivirus" class="form-control" style="width: 100px !important;"> <option value="">Selecione</option> <option value="S">Sim</option> <option value="N">Não</option> </select> </div> </div> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Valor do Frete:</label> <input type="text" class="form-control w-auto" name="valor_frete" id="valor_frete" onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Valor do Seguro:</label> <input type="text" class="form-control w-auto" name="valor_seguro" id="valor_seguro" onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> </div> </div> <div class="row gy-3"> <div class="d-flex flex-wrap gap-3 align-items-center"> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Marca:</label> <select name="gre_marca_id" id="gre_marca_id" class="form-control" required onchange="pegaModelo(this.value)" style="width: 150px !important;" > <option value="">Selecione</option> </select> <input type="text" name="nome_marca" id="nome_marca" class="form-control placeholder-verde d-none" placeholder="Digite nova marca" style="width: 150px;">  <button type="button" class="btn btn-outline-primary btn-sm" id="btnToggleCampoMarca" title="Novo" onclick="alternarCampoMarca()"> <i class="fas fa-plus"></i> </button> </div> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Modelo:</label> <select name="gre_mod_id" id="gre_mod_id" class="form-control" required onchange="pegaProd(this.value)" style="width: 200px;"> <option value="">Modelos Existentes</option> </select> <input type="text" name="nome_modelo" id="nome_modelo" class="form-control placeholder-verde d-none" placeholder="Digite novo modelo" style="width: 350px;">  <button type="button" class="btn btn-outline-primary btn-sm" id="btnToggleCampo" title="Novo" onclick="alternarCampoModelo()"> <i class="fas fa-plus"></i> </button> </div> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Especificações:</label> <select name="gre_prod_id" id="gre_prod_id" class="form-control" required style="width: 300px !important;" onchange="pegaPreco(this.value)"> <option value="">Selecione</option> </select> <input type="text" name="nome_produto" id="nome_produto" class="form-control placeholder-verde d-none"placeholder="Digite nova especificação" style="width: 350px !important;">  <button type="button" class="btn btn-outline-primary btn-sm" id="btnToggleCampo" title="Novo" onclick="alternarCampoEspec()"> <i class="fas fa-plus"></i> </button> </div> </div> </div> <div class="row gy-3"> <div class="d-flex flex-wrap gap-3 align-items-center"> <div class="d-flex align-items-center"> <label class="me-2"><span class="text-danger">*</span>Valor do Equipamento:</label> <input name="custo_medio" id="custo_medio" type="text" class="form-control" required onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> <!-- <div class="d-flex align-items-center"> <label class="me-2" style="white-space: nowrap;"><span class="text-danger">*</span>Franquia/mês:</label> <input name="franquia" id="num_4a" type="text" class="form-control" required style="width: 100px !important;" > </div> </div> --> <div class="d-flex align-items-center"> <label id="lb1" class="me-2" style="white-space: nowrap;"><span class="text-danger">*</span>Preço:</label> <input name="preco1" id="preco1" type="text" class="form-control" required onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> <div class="d-flex align-items-center"> <label id="lb2" class="me-2" style="white-space: nowrap;"><span class="text-danger">*</span>Preço:</label> <input name="preco2" id="preco2" type="text" class="form-control" required onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> <div class="d-flex align-items-center"> <label id="lb3" class="me-2" style="white-space: nowrap;"><span class="text-danger">*</span>Preço:</label> <input name="preco3" id="preco3" type="text" class="form-control" required onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> </div> </div> </div> <!-- <div class="row gy-1"> <div class="d-flex flex-wrap gap-3 align-items-center"> <div class="d-flex align-items-center"> <label class="me-2" style="white-space: nowrap;">Adicional 36 meses:</label> <input name="adic36" id="adic36" type="text" class="form-control" onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> <div class="d-flex align-items-center"> <label class="me-2" style="white-space: nowrap;">Adicional 48 meses:</label> <input name="adic48" id="adic48" type="text" class="form-control" onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;"> </div> <div class="d-flex align-items-center"> <label class="me-2" style="white-space: nowrap;">Adicional 60 meses:</label> <input name="adic60" id="adic60" type="text" class="form-control" onKeyPress="return(MascaraMoeda(this, '.', ',', event))" style="width: 100px !important;" > </div> </div> </div> --> <div id="divobs"> <div class="row gy-3"> <div class="form-group col-md-6"> <label class="me-2">Observação:</label> <input name="observacao" id="observacao" type="text" class="form-control"> </div> </div> </div> <div id="divcond"> <div class="row gy-3"> <label class="me-2"><span class="text-danger">*</span>Condições de Faturamento:</label> <div class="form-group col-md-6"> <textarea class="form-control" name="condicoes" id="condicoes" placeholder="Digite as condições aqui..."rows="10" cols="100" <?= !empty($valorForm['condicoes']) ? 'readonly' : '' ?>><?= isset($valorForm['condicoes']) ? htmlspecialchars(ltrim($valorForm['condicoes'])) : '' ?></textarea> </div> </div> </div> </div> <div class="row gy-3"> <div class="grupo-controle" style="width: 100%; font-family: Arial; text-align: left;"> <p style="font-size: 0.8em; margin-bottom: 8px;"> <span style="color: red;">*</span> Campo obrigatório </p> <div class="botoes-acoes" style="display: flex; gap: 8px; flex-wrap: wrap; justify-content: flex-start;"> <button type="submit" name="Limpar" id="limpar" class="btn btn-primary btn-sm" formnovalidate>Limpar</button> <button name="Calcular" id="calc" value="calc" type="button" class="btn btn-success btn-sm" onclick="calculo()">Calcular</button> <button name="CadOrcamento" id="acao" value="salvar" type="submit" onclick="incluirItem()" class="btn btn-warning btn-sm"> Incluir Item </button> </div> </div> </div> <div id="modalCalculo" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background-color: rgba(0,0,0,0.6); justify-content:center; align-items:center; z-index:9999;"> <div style="background:#fff; padding:20px; max-width:600px; border-radius:10px; overflow:auto;"> <h2 style="text-align:center;">Memória do cálculo</h2> <div id="conteudoModal"></div> <div style="text-align:center; margin-top:10px;"> <button class="btn btn-success" type="button" onclick="fecharModal()">Fechar</button> <button class="btn btn-primary" onclick="exportarParaExcel()">Exportar para Excel</button> </div> </div> </div> </div> </div> </div> <div class="tab-pane fade" id="aba-itens" role="tabpanel"> <table class="table table-bordered table-striped mt-3"> <thead class="table-light"> <?php if(isset($this->Dados['select']['dadosTab'][0]['nome_cliente'])) { ?> <tr> <th colspan="6" style="text-align: center;"> <?php echo 'Cliente: '.$this->Dados['select']['dadosTab'][0]['nome_cliente']; ?></th> </tr> <?php } ?> <tr> <th>ID</th> <th>Marca</th> <th>Modelo</th> <th>Especificação</th> <th>Assinatura Mensal</th> <th>Prazo</th> </tr> </thead> <?php if(!empty($this->Dados['select']['dadosTab'])){ foreach ($this->Dados['select']['dadosTab'] as $item): ?> <tr> <td><?= htmlspecialchars($item['id_item']) ?></td> <td><?= htmlspecialchars($item['nome_marca']) ?></td> <td><?= htmlspecialchars($item['nome_modelo']) ?></td> <td><?= htmlspecialchars($item['nome_produto']) ?></td> <td style="text-align: center;"><?= htmlspecialchars($item['preco1']) ?></td> <td style="text-align: center;"><?= htmlspecialchars($item['prazo']) ?></td> </tr> <?php endforeach; ?> <?php }?> <!-- Linhas serão adicionadas aqui --> </tbody> </table> </div> <!-- Modal --> <div class="modal fade" id="modalNovoCliente" tabindex="-1" aria-labelledby="modalNovoClienteLabel" aria-hidden="true"> <div class="modal-dialog modal-xl"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="modalNovoClienteLabel">Cadastrar Cliente</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Fechar"></button> </div> <div class="modal-body"> <div class="row gy-3"> <div class="form-group col-md-2"> <label><span class="text-danger">*</span>Tipo Cliente</label> <select name="mo_gre_tipo_id" id="mo_gre_tipo_id" class="form-control" required onchange="atualizarMoDocumento(this.value)"> <option value="">Selecione</option> <?php foreach ($this->Dados['select']['pessoa'] as $pessoa) { extract($pessoa); echo "<option value='$id_pessoa'>$nome_pessoa</option>"; } ?> </select> </div> <div class="form-group col-md-4"> <label id="mo_nome" ><span class="text-danger">*</span>Nome:</label> <input type="text" name="mo_nome" id="mo_nome" class="form-control" placeholder="Nome do Cliente" required value="<?php if (isset($valorForm['nome'])) { echo $valorForm['nome']; }?>"> </div> <div class="form-group col-md-2"> <label id="mo_lconta"><span class="text-danger">*</span><span id="labelMoDocumento">Contato</span></label> <input type="text" name="mo_contato" id="mo_contato" class="form-control" value="<?php if (isset($valorForm['contato'])) { echo $valorForm['contato']; }?>" > </div> <div id="mo_cpcnpj" class="form-group col-md-2"> <label><span class="text-danger">*</span><span id="labelMoDocumento">CNPJ</span></label> <input type="text" name="mo_cnpj" id="cnpj" class="form-control" onchange="valCNPJ(this.value), verCnpjDuplo(this.value)" value="<?php if (isset($valorForm['cnpj'])) { echo $valorForm['cnpj']; }?>" > </div> <div id="mo_cpcpf" class="form-group col-md-2"> <label><span class="text-danger">*</span><span id="labelMoDocumento">CPF</span></label> <input type="text" name="mo_cpf" id="cpf" class="form-control" onchange="valCPF(this.value,'N') , verCpfDuplo(this.value,'cpf')" value="<?php if (isset($valorForm['cpf'])) { echo $valorForm['cpf']; }?>"> </div> </div> <div class="row gy-3"> <div class="form-group col-md-2"> <label><span class="text-danger">* </span>CEP</label> <input name="mo_cep" id="cep" type="text" class="form-control" placeholder="Somente número" onchange="javascript:buscacep(this.value)" value="<?php if (isset($valorForm['cep'])) { echo $valorForm['cep']; } ?>" required> </div> <div class="form-group col-md-5"> <label><span class="text-danger">*</span>Endereço</label> <input name="mo_endereco" type="text" id="rua" class="form-control" placeholder="Nome da Rua, Av..." value="<?php if (isset($valorForm['endereco'])) { echo $valorForm['endereco']; } ?>" required> </div> <div class="form-group col-md-1"> <label><span class="text-danger">*</span>Número</label> <input name="mo_numero" type="text" class="form-control" value="<?php if (isset($valorForm['numero'])) { echo $valorForm['numero']; } ?>" required> </div> <div class="form-group col-md-2"> <label> Complemento</label> <input name="mo_complemento" type="text" class="form-control" value="<?php if (isset($valorForm['complemento'])) { echo $valorForm['complemento']; } ?>"> </div> </div> <div class="row gy-3"> <div class="form-group col-md-3"> <label><span class="text-danger">*</span>Bairro</label> <input name="mo_bairro" type="text" id="bairro" class="form-control" placeholder="Nome do bairro" value="<?php if (isset($valorForm['bairro'])) { echo $valorForm['bairro']; } ?>" required> </div> <div class="form-group col-md-2"> <label><span class="text-danger">*</span><label>Município</label> <input name="mo_municipio" type="text" id="municipio" class="form-control" required readonly> </div> <div class="form-group col-md-1"> <label><span class="text-danger">*</span><label >UF</label> <input name="mo_uf" type="text" id="uf" class="form-control text-center" required readonly> <input name="mo_municipio_id" type="hidden" id="municipio_id"> </div> </div> <div class="row gy-3"> <div class="form-group col-md-3"> <label>Fone Comercial Fixo</label> <input name="mo+fone" id="fone"type="text" class="form-control" placeholder="DDD+numero" value="<?php if (isset($valorForm['fone'])) { echo $valorForm['fone']; } ?>" > </div> <div class="form-group col-md-3"> <label><span class="text-danger">*</span>Celular Contato</label> <input name="mo_celular" id="cel2" type="text" class="form-control" placeholder="Celular do contato" value="<?php if (isset($valorForm['celular'])) { echo $valorForm['celular']; } ?>" required> </div> <div class="form-group col-md-4"> <label><span class="text-danger">*</span> E-mail</label> <input name="mo_email" type="email" class="form-control" placeholder="E-mail" value="<?php if (isset($valorForm['email'])) { echo $valorForm['email']; } ?>" required> </div> </div> <div> <p><span class="text-danger">*</span>Campo obrigatório</p> <button type="button" class="btn btn-outline-warning m-2" id="btnGravarMo">Salvar</button> <button name="Limpar" type="reset" class="btn btn-outline-info">Limpar</button> </div> </div> </div> </div> </div> </form> </div> </div> </div> </body> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> document.getElementById('btnToggleCampoCliente').addEventListener('click', function () { const modal = new bootstrap.Modal(document.getElementById('modalNovoCliente')); modal.show(); document.getElementById("mo_cpcpf").style.display = 'none'; //document.getElementById("cpcnpj").style.display = 'none'; $('#cnpj').prop('required', true); }); document.addEventListener("DOMContentLoaded", function () { const clienteInput = document.getElementById("cliente_input"); const datalist = document.getElementById("clientes"); if (clienteInput && datalist) { clienteInput.addEventListener("input", function () { const valorSelecionado = clienteInput.value.trim(); const opcoes = datalist.options; for (let i = 0; i < opcoes.length; i++) { if (opcoes[i].value === valorSelecionado) { const contato = opcoes[i].dataset.contato || ''; const celular = opcoes[i].dataset.celular || ''; const email = opcoes[i].dataset.email || ''; document.getElementById("contato").value = contato; document.getElementById("cel").value = celular; document.getElementById("email").value = email; console.log("✅ Cliente selecionado:", valorSelecionado); console.log("📞 Contato:", contato, "📱 Celular:", celular, "✉️ Email:", email); break; } } }); } }); function verCpfDuplo(cpf,cpo) { var enderecoa = document.getElementById("urladm").value; var cpfl = cpf.replace(/\D/g, ''); var jsonData = null; // Variável para armazenar os dados JSON $.ajax({ type: "GET", data: { cpf: cpfl, tabela: 'gre_clientes', cpo: cpo, }, url: enderecoa + "vendor/api/ver_cpfDuplo.php", async: false, // ⚠️ Bloqueia o carregamento, melhor evitar! success: function(text) { try { jsonData = JSON.parse(text); } catch (error) { console.error("Erro ao processar resposta JSON:", error); } } }); // Verificação do CPF fora da requisição AJAX if (jsonData && jsonData.cont > 0) { Swal.fire({ title: 'Erro!', text: 'CPF Já existe cadastrado!', icon: 'error', confirmButtonText: 'OK' }).then(() => { document.getElementById("cpf").value = ""; document.getElementById("cpf").focus(); }); return; // Interrompe a execução corretamente } } function verCnpjDuplo(cnpj) { var enderecoa = document.getElementById("urladm").value; var cnpjl = cnpj.replace(/\D/g, ''); // alert('cpfDuplo: ' +cpfl); // alert(enderecoa); $(document).ready(function() { var responsef = ''; $.ajax({ type: "GET", data : { cnpj: cnpjl, tabela: 'gre_clientes', }, url: enderecoa + "vendor/api/ver_cnpjDuplo.php", async: false, success: function(text) { responsef = text; console.log(responsef); let jsonData = JSON.parse(responsef); console.log(jsonData.cont); // Saída: "1" if(jsonData.cont >0 ){ mostrarAlerta('Erro!', 'CNPJ Já existe cadastrado.', 'error'); //alert('CNPJ Já existe cadastrado!!'); document.getElementById("cnpj").value = ""; document.getElementById("cnpj").focus(); return; } } }); }); } function atualizarMoDocumento(mo_tipo) { const select = document.getElementById("mo_gre_tipo_id"); const textoSelecionado = select.options[select.selectedIndex].text; //document.getElementById("labelModal").innerHTML = 'Tipo: ' + textoSelecionado; if (mo_tipo === '1') { // Pessoa Jurídica document.getElementById("mo_cpcnpj").style.display = "block"; document.getElementById("mo_cpcpf").style.display = "none"; document.getElementById("mo_nome").innerHTML = "<span class='text-danger' style='font-size: 0.8em;'>*</span> Razão Social:"; document.getElementById("mo_cliente_input").placeholder = "Razão Social"; document.getElementById("mo_lconta").innerHTML = "<span class='text-danger'>*</span>Contato"; document.getElementById("mo_contato").placeholder = "Nome do Contato"; // Mostrar CNPJ, esconder CPF } else { document.getElementById("mo_cpcnpj").style.display = "none"; document.getElementById("mo_cpcpf").style.display = "block"; // Pessoa Física document.getElementById("mo_nome").innerHTML = "<span class='text-danger'>*</span>Nome"; document.getElementById("mo_cliente_input").placeholder = "Nome Completo"; document.getElementById("mo_lconta").innerHTML = "<span class='text-danger'>*</span>Nome Social"; document.getElementById("mo_contato").placeholder = "Chamar de"; // Mostrar CPF, esconder CNPJ } } $("#btnGravarMo").on("click", function () { const form = document.getElementById("form_orcamento"); if (!form) { console.error("❌ Formulário com ID 'form_orcamento' não encontrado."); return; } const tipoCliente = form.querySelector("[name='mo_gre_tipo_id']").value.trim(); const cnpj = form.querySelector("[name='mo_cnpj']").value.trim(); const cpf = form.querySelector("[name='mo_cpf']").value.trim(); const inconsistencias = []; const camposMo = form.querySelectorAll("[name^='mo_']"); const dados = {}; // Captura todos os campos camposMo.forEach(campo => { if (campo && campo.name) { const nomeSemPrefixo = campo.name.replace(/^mo_/, ''); const valor = campo.value.trim(); dados[nomeSemPrefixo] = valor; } }); const usuarioId = "<?php echo $_SESSION['usuario_id']; ?>"; if (typeof usuarioId !== 'undefined') { dados['usu_created'] = usuarioId; } const emprId = "<?php echo $_SESSION['id_user']; ?>"; if (typeof emprId !== 'undefined') { dados['empr_id'] = emprId; } // Log antes da consistência console.log("📋 Todos os campos capturados:"); Object.entries(dados).forEach(([campo, valor]) => { console.log(`→ ${campo}: "${valor}"`); }); // Validação condicional de CPF/CNPJ if (tipoCliente === '1' && cnpj === '') { inconsistencias.push("CNPJ"); } if (tipoCliente !== '1' && cpf === '') { inconsistencias.push("CPF"); } // Validação dos demais campos obrigatórios camposMo.forEach(campo => { if ( campo.name !== 'mo_fone' && campo.name !== 'mo_complemento' && campo.name !== 'mo_cnpj' && campo.name !== 'mo_cpf' && campo.name !== 'mo_gre_tipo_id' ) { if (campo.value.trim() === '') { inconsistencias.push(campo.name.replace(/^mo_/, '')); } } }); // Exibe alerta se houver inconsistências if (inconsistencias.length > 0) { const mensagem = inconsistencias.join(", "); mostrarAlerta('ERRO\nCampos Obrigatórios', mensagem, 'error'); return; } // ✅ Remove campos vazios antes de enviar for (const key in dados) { if (dados.hasOwnProperty(key)) { const valor = dados[key]; if (valor === null || valor === undefined || valor.trim?.() === '') { delete dados[key]; } } } console.log("✅ Dados prontos para envio (sem campos vazios):", dados); $.ajax({ type: "POST", url: "<?php echo URLADM . 'vendor/api/gravaModalCliente.php'; ?>", data: dados, dataType: "json", success: function (response) { console.log("📦 Resposta do servidor:", response); const modal = bootstrap.Modal.getInstance(document.getElementById('modalNovoCliente')); if (modal) modal.hide(); form.reset(); if (response.status === 'success') { const cliente = response.id_cliente; const nome = dados['nome']; const lista = document.getElementById("listaClientes"); if (lista) { const item = document.createElement("div"); item.className = "alert alert-success mt-2"; item.innerHTML = `Cliente <strong>${nome}</strong> cadastrado com sucesso! (ID: ${cliente})`; lista.appendChild(item); } // Preenche os campos da view com os dados gravados document.getElementById("cliente_input").value = dados['nome'] || ''; document.getElementById("contato").value = dados['contato'] || ''; document.getElementById("cel").value = dados['celular'] || ''; document.getElementById("email").value = dados['email'] || ''; } else { mostrarAlerta('ERRO', response.mensagem || 'Erro inesperado ao gravar.', 'error'); } }, error: function (xhr, status, error) { console.error("❌ Erro na requisição AJAX:", error); mostrarAlerta('ERRO', 'Falha na comunicação com o servidor.', 'error'); } }); }); </script> <script> document.getElementById("divobs").style.display = 'none'; document.getElementById("acao").style.display = 'none'; document.getElementById("offi").style.display = 'none'; verificarCamposObrigatoriosOff(); document.getElementById("viri").style.display = 'none'; verificarCamposObrigatoriosViri(); document.getElementById("divcond").style.display = 'none'; const clientes = <?= json_encode($this->Dados['select']['cliente']) ?>; // Evento para capturar seleção ou digitação final no input document.getElementById("cliente_input").addEventListener("change", function () { const nomeSelecionado = this.value.trim().toUpperCase(); document.getElementById("cliente_input").value = nomeSelecionado; document.getElementById("novo_cliente").value = nomeSelecionado; const cliente = clientes.find(c => c.nome_cliente.toUpperCase() === nomeSelecionado); if (cliente) { pegaDadosCli(cliente); } else { alert("Cliente não encontrado."); } }); function pegaDadosCli(cliente) { const clienteEmail = cliente.email_cliente || ""; const clienteCep2 = cliente.cep_cliente || ""; const clienteContato = cliente.contato_cliente || ""; const clienteCelular = cliente.celular_cliente || ""; document.getElementById("cepdestino").value = formatarCEP(clienteCep2); document.getElementById("email").value = clienteEmail; document.getElementById("contato").value = clienteContato; document.getElementById("cel").value = clienteCelular; consultarDadosCompletos(clienteCep2); } // Formata o CEP como 99999-999 function formatarCEP(valor) { const cepLimpo = valor.replace(/\D/g, ''); return cepLimpo.replace(/^(\d{5})(\d{3})$/, '$1-$2'); } // Consulta dados de CEP usando API async function consultarCep(cep) { const response = await fetch(`https://cep.awesomeapi.com.br/json/${cep}`); return await response.json(); } // Calcula distância entre dois CEPs async function consultarDadosCompletos(cep2) { const cep1 = document.getElementById("cep1").value.trim(); const origem = await consultarCep(cep1); const destino = await consultarCep(cep2); if (origem.lat && origem.lng && destino.lat && destino.lng) { const distancia = haversine(+origem.lat, +origem.lng, +destino.lat, +destino.lng); document.getElementById("distancia").value = distancia.toFixed(2) + " km"; } else { console.warn("Coordenadas não disponíveis."); } } function haversine(lat1, lon1, lat2, lon2) { const R = 6371; const dLat = (lat2 - lat1) * Math.PI / 180; const dLon = (lon2 - lon1) * Math.PI / 180; const a = Math.sin(dLat / 2) ** 2 + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * Math.sin(dLon / 2) ** 2; const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return R * c; } document.getElementById("franquia").addEventListener("input", function () { this.value = this.value.replace(/\D/g, ""); }); document.getElementById("limpar").addEventListener("click", () => { // alert('aqui'); fetch("", { method: "POST", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "limpar=sim" }) .then(response => response.text()) .then(data => { document.getElementById("condicoes").value = ""; document.querySelector("form").reset(); document.getElementById("divobs").style.display = 'none'; document.getElementById("acao").style.display = 'none'; document.getElementById("offi").style.display = 'none'; verificarCamposObrigatoriosOff(); document.getElementById("viri").style.display = 'none'; verificarCamposObrigatoriosViri(); document.getElementById("divcond").style.display = 'none'; }) .catch(error => console.error("Erro:", error)); }); let contador = 1; document.getElementById("condicoes").addEventListener("keydown", function(e) { if (e.key === "Enter") { e.preventDefault(); // Impede quebra padrão contador++; const campo = e.target; const inicio = campo.selectionStart; const textoAntes = campo.value.substring(0, inicio); const textoDepois = campo.value.substring(inicio); const novaLinha = `\n${contador}. `; campo.value = textoAntes + novaLinha + textoDepois; campo.selectionStart = campo.selectionEnd = inicio + novaLinha.length; } }); // Assumindo que os dados dos clientes já foram renderizados no PHP function incluirItem() { alert('aqui inclui'); // if (campos.value.trim() === "") { // mostrarAlerta('ERRO', "Condições de fornecimento Obrigatório", "error"); // campos.focus(); // e.preventDefault(); // <-- Isso sim impede o submit! // return; // } // incluir itens const categoria = document.getElementById("gre_cat_id"); console.log('categoria:'+categoria); const categoriaTexto = categoria.options[categoria.selectedIndex]?.text; //alert('categoriaTexto'+categoriaTexto); const marcaTexto = document.getElementById("gre_marca_id").classList.contains("d-none") ? document.getElementById("nome_marca").value : document.getElementById("gre_marca_id").options[document.getElementById("gre_marca_id").selectedIndex]?.text; const nomeModelo = document.getElementById("nome_modelo").value; if (!nomeModelo.trim()) { var modeloTexto = document.getElementById("gre_mod_id").classList.contains("d-none") ? document.getElementById("nome_modelo").value : document.getElementById("gre_mod_id").options[document.getElementById("gre_mod_id").selectedIndex]?.text; } else { var modeloTexto = nomeModelo; } console.log('modeloTexto:'+modeloTexto); //alert('modeloTexto'+modeloTexto); const especificacaoTexto = document.getElementById("gre_prod_id").classList.contains("d-none") ? document.getElementById("nome_produto").value : document.getElementById("gre_prod_id").options[document.getElementById("gre_prod_id").selectedIndex]?.text; const custoMedio = document.getElementById("custo_medio").value; //alert('custoMedio '+custoMedio); const prazo = document.getElementById("gre_prazo_id"); const prazoTexto = categoria.options[prazo.selectedIndex]?.text; console.log('prazo:'+prazo); console.log('prazoTexto:'+prazoTexto); //alert('PRAZO '+prazoTexto); if (!categoria.value || !marcaTexto || !modeloTexto || !especificacaoTexto || !custoMedio || !prazoTexto) { alert("Preencha todos os campos obrigatórios."); return; } alert('especificacaoTexto antes da tabela '+especificacaoTexto); } function alternarCampoCliente() { const inputDatalist = document.getElementById("cliente_input"); // campo com datalist const inputNovo = document.getElementById("novo_cliente"); // campo para cliente manual const inputContato = document.getElementById("novo_contato"); const inputCelular = document.getElementById("cel2"); const inputEmail = document.getElementById("novo_email"); const inputContatoAut = document.getElementById("contato"); const inputCelularAut = document.getElementById("cel"); const inputEmailAut = document.getElementById("email"); const btnToggle = document.getElementById("btnToggleCampoCliente"); const icon = btnToggle.querySelector("i"); const usandoDatalist = !inputDatalist.classList.contains("d-none"); if (usandoDatalist) { // Oculta campos com datalist inputDatalist.classList.add("d-none"); inputDatalist.removeAttribute("required"); inputContatoAut.classList.add("d-none"); inputContatoAut.removeAttribute("required"); inputCelularAut.classList.add("d-none"); inputCelularAut.removeAttribute("required"); inputEmailAut.classList.add("d-none"); inputEmailAut.removeAttribute("required"); // Mostra inputs para cliente manual inputNovo.classList.remove("d-none"); inputNovo.setAttribute("required", "required"); inputContato.classList.remove("d-none"); inputContato.setAttribute("required", "required"); inputCelular.classList.remove("d-none"); inputCelular.setAttribute("required", "required"); inputEmail.classList.remove("d-none"); inputEmail.setAttribute("required", "required"); icon.classList.replace("fa-plus", "fa-arrow-left"); btnToggle.title = "Voltar para seleção"; } else { // Oculta inputs manuais inputNovo.classList.add("d-none"); inputNovo.removeAttribute("required"); inputContato.classList.add("d-none"); inputContato.removeAttribute("required"); inputCelular.classList.add("d-none"); inputCelular.removeAttribute("required"); inputEmail.classList.add("d-none"); inputEmail.removeAttribute("required"); // Mostra datalist e campos automáticos inputDatalist.classList.remove("d-none"); inputDatalist.setAttribute("required", "required"); inputContatoAut.classList.remove("d-none"); inputContatoAut.setAttribute("required", "required"); inputCelularAut.classList.remove("d-none"); inputCelularAut.setAttribute("required", "required"); inputEmailAut.classList.remove("d-none"); inputEmailAut.setAttribute("required", "required"); icon.classList.replace("fa-arrow-left", "fa-plus"); btnToggle.title = "Novo Cliente"; // Reaplica os dados do cliente selecionado no datalist const valor = inputDatalist.value.trim().toLowerCase(); const cliente = clientes.find(c => c.nome_cliente.toLowerCase() === valor); if (cliente) { pegaDadosCli(cliente); } } } function alternarCampoMarca() { const selectMarca = document.getElementById("gre_marca_id"); const inputMarca = document.getElementById("nome_marca"); const selectModelo = document.getElementById("gre_mod_id"); const inputModelo = document.getElementById("nome_modelo"); const selectDescricao = document.getElementById("gre_prod_id"); const inputDescricao = document.getElementById("nome_produto"); const btnToggle = document.getElementById("btnToggleCampo"); const icon = btnToggle.querySelector("i"); const mostrandoSelect = !selectMarca.classList.contains("d-none"); if (mostrandoSelect) { // Oculta selects selectMarca.classList.add("d-none"); selectMarca.removeAttribute("required"); selectModelo.classList.add("d-none"); selectModelo.removeAttribute("required"); selectDescricao.classList.add("d-none"); selectDescricao.removeAttribute("required"); // Mostra inputs inputMarca.classList.remove("d-none"); inputMarca.setAttribute("required", "required"); inputModelo.classList.remove("d-none"); inputModelo.setAttribute("required", "required"); inputDescricao.classList.remove("d-none"); inputDescricao.setAttribute("required", "required"); // Atualiza botão icon.classList.replace("fa-plus", "fa-arrow-left"); btnToggle.title = "Voltar para seleção"; } else { // Oculta inputs inputMarca.classList.add("d-none"); inputMarca.removeAttribute("required"); inputModelo.classList.add("d-none"); inputModelo.removeAttribute("required"); inputDescricao.classList.add("d-none"); inputDescricao.removeAttribute("required"); // Mostra selects selectMarca.classList.remove("d-none"); selectMarca.setAttribute("required", "required"); selectModelo.classList.remove("d-none"); selectModelo.setAttribute("required", "required"); selectDescricao.classList.remove("d-none"); selectDescricao.setAttribute("required", "required"); // Atualiza botão icon.classList.replace("fa-arrow-left", "fa-plus"); btnToggle.title = "Novo modelo"; } } function alternarCampoModelo() { const selectModelo = document.getElementById("gre_mod_id"); const inputModelo = document.getElementById("nome_modelo"); const selectDescricao = document.getElementById("gre_prod_id"); const inputDescricao = document.getElementById("nome_produto"); const btnToggle = document.getElementById("btnToggleCampo"); const icon = btnToggle.querySelector("i"); const mostrandoSelect = !selectModelo.classList.contains("d-none"); if (mostrandoSelect) { // Oculta selects selectModelo.classList.add("d-none"); selectModelo.removeAttribute("required"); selectDescricao.classList.add("d-none"); selectDescricao.removeAttribute("required"); // Mostra inputs inputModelo.classList.remove("d-none"); inputModelo.setAttribute("required", "required"); inputDescricao.classList.remove("d-none"); inputDescricao.setAttribute("required", "required"); // Atualiza botão icon.classList.replace("fa-plus", "fa-arrow-left"); btnToggle.title = "Voltar para seleção"; } else { // Oculta inputs inputModelo.classList.add("d-none"); inputModelo.removeAttribute("required"); inputDescricao.classList.add("d-none"); inputDescricao.removeAttribute("required"); // Mostra selects selectModelo.classList.remove("d-none"); selectModelo.setAttribute("required", "required"); selectDescricao.classList.remove("d-none"); selectDescricao.setAttribute("required", "required"); // Atualiza botão icon.classList.replace("fa-arrow-left", "fa-plus"); btnToggle.title = "Novo modelo"; } } function alternarCampoEspec() { const selectDescricao = document.getElementById("gre_prod_id"); const inputDescricao = document.getElementById("nome_produto"); const btnToggle = document.getElementById("btnToggleCampo"); const icon = btnToggle.querySelector("i"); const mostrandoSelect = !selectDescricao.classList.contains("d-none"); if (mostrandoSelect) { // Oculta selects selectDescricao.classList.add("d-none"); selectDescricao.removeAttribute("required"); // Mostra inputs inputDescricao.classList.remove("d-none"); inputDescricao.setAttribute("required", "required"); // Atualiza botão icon.classList.replace("fa-plus", "fa-arrow-left"); btnToggle.title = "Voltar para seleção"; } else { // Oculta inputs inputDescricao.classList.add("d-none"); inputDescricao.removeAttribute("required"); // Mostra selects selectDescricao.classList.remove("d-none"); selectDescricao.setAttribute("required", "required"); // Atualiza botão icon.classList.replace("fa-arrow-left", "fa-plus"); btnToggle.title = "Novo modelo"; } } function limpaDados() { document.getElementById("input_cliente").value = ""; document.getElementById("email").value = ""; document.getElementById("contato").value = ""; //document.getElementById("gre_tipo_id").value = ""; document.getElementById("cel").value = ""; document.getElementById("data_validade").value = ""; document.getElementById("data_validade").value = ""; // Limpa o <select> document.getElementById("cliente_id").value = ""; //document.getElementById("gre_tipo_id").disabled = false; document.getElementById("cliente_id").disabled = false; document.querySelector("form").submit(); // faz o submit do formulário } const botaoLimpar = document.querySelector('button[type="reset"]'); botaoLimpar.addEventListener('click', function () { // Limpa o array ValorForm = []; }); function atualizarDocumento(tipo) { //alert(tipo); const select = document.getElementById("gre_tipo_id"); const textoSelecionado = select.options[select.selectedIndex].text; document.getElementById("labelModal").innerHTML = 'Tipo: '+textoSelecionado; // alert(textoSelecionado); if(tipo === '1') { document.getElementById("nome").style.whiteSpace = "nowrap"; document.getElementById("nome").innerHTML = "<span class='text-danger' style='font-size: 0.8em;'>*</span> Razão Social: "; document.getElementById("cliente_input").placeholder = "Razão Social"; document.getElementById("lconta").innerHTML = " <span class='text-danger'>*</span>Contato"; document.getElementById("contato").placeholder = "Nome do Contato"; }else{ document.getElementById("nome").innerHTML = " <span class='text-danger'>*</span>Nome"; document.getElementById("cliente_input").placeholder = "Nome Completo"; document.getElementById("lconta").innerHTML = " <span class='text-danger'>*</span>Nome Social"; document.getElementById("contato").placeholder = "Chamar de "; } } function verificarCamposObrigatoriosOff() { const divOffi = document.getElementById("offi"); // Verifica se a div está visível if (divOffi.style.display === 'block') { // Torna os campos dentro da div obrigatórios const campos = divOffi.querySelectorAll("select"); campos.forEach(campo => campo.required = true); } else { // Remove o 'required' se a div estiver oculta const campos = divOffi.querySelectorAll("select"); campos.forEach(campo => campo.required = false); } } function verificarCamposObrigatoriosViri() { const divViri = document.getElementById("viri"); // Verifica se a div está visível if (divViri.style.display === 'block') { // Torna os campos dentro da div obrigatórios const campos = divViri.querySelectorAll("select"); campos.forEach(campo => campo.required = true); } else { // Remove o 'required' se a div estiver oculta const campos = divViri.querySelectorAll("input, select, textarea"); campos.forEach(campo => campo.required = false); } } function pegaMarca(cat) { //alert('aqui '+cat); const textod = document.getElementById("data_validade").value; if (textod === "") { mostrarAlerta('ERRO', "Data de Validade Obrigatória", "error"); document.getElementById('gre_cat_id').value = ''; return; } const selecti = document.getElementById("gre_prazo_id"); const textoi = selecti.options[selecti.selectedIndex].text; if (textoi === "Selecione") { mostrarAlerta('ERRO', "Prazo de Contrato Obrigatório", "error"); document.getElementById('gre_cat_id').value = ''; return; } const [prazoi, prazo2i, prazo3i] = textoi.split("/").map(Number); if ([prazoi, prazo2i, prazo3i].some(isNaN)) { mostrarAlerta('ERRO', "Formato de prazo inválido", "error"); return; } document.getElementById("prazo1").value = prazoi; document.getElementById("prazo2").value = prazo2i; document.getElementById("prazo3").value = prazo3i; const select = document.getElementById("gre_cat_id"); const opcaoSelecionada = select.options[select.selectedIndex]; const percDepri = opcaoSelecionada.dataset.depr; const percManut = opcaoSelecionada.dataset.manut; const percMargem = opcaoSelecionada.dataset.margem; const office = opcaoSelecionada.dataset.office; const antivirus = opcaoSelecionada.dataset.antivirus; //alert('antivirus 776: '+antivirus ); document.getElementById("temoffice").value = office; document.getElementById("temantivirus").value = antivirus; //alert('antivirus 780: '+antivirus ); if (office == 'S') { document.getElementById("offi").style.display = 'block'; }else{ document.getElementById("offi").style.display = 'none'; } verificarCamposObrigatoriosOff(); if (antivirus == 'S') { document.getElementById("viri").style.display = 'block'; }else{ document.getElementById("viri").style.display = 'none'; } verificarCamposObrigatoriosViri(); document.getElementById("perc_depreciacao").value = percDepri+"%"; const manutRaw = opcaoSelecionada.dataset.manut; // Ex: "50.00" const manutNum = parseFloat(manutRaw); // Converte para número if (!isNaN(manutNum)) { const manutFormatada = manutNum.toLocaleString("pt-BR", {minimumFractionDigits: 1,maximumFractionDigits: 2}) + "%"; document.getElementById("perc_manutencao").value = manutFormatada; } else { document.getElementById("perc_manutencao").value = '0.00'; } const margemRaw = opcaoSelecionada.dataset.margem; // Ex: "50.00" const margemNum = parseFloat(margemRaw); // Converte para número if (!isNaN(margemNum)) { const margemFormatada = margemNum.toLocaleString("pt-BR", {minimumFractionDigits: 1,maximumFractionDigits: 2}) + "%"; document.getElementById("perc_margem").value = margemFormatada; } else { if (!isundefined(margemNum)) { mostrarAlerta("ERRO", "Margem inválida no dataset", "error"); } } var obj = <?php echo json_encode($this->Dados['select']['marca']); ?>; var element = document.getElementById("gre_marca_id"); element.innerHTML = ''; // Limpa opções existentes var node = document.createElement("option"); var textnode = document.createTextNode("Selecione"); node.setAttribute("value", ""); node.appendChild(textnode); element.appendChild(node); for (var i = 0; i < obj.length; i++) { if(obj[i].id_cat === cat) { var node = document.createElement("option"); var textnode = document.createTextNode(obj[i].nome_marca); node.setAttribute("value", obj[i].id_marca); node.appendChild(textnode); element.appendChild(node); } } } function pegaModelo(marca) { var obj = <?php echo json_encode($this->Dados['select']['modelo']); ?>; const select = document.getElementById("gre_marca_id"); const textoSelecionado = select.options[select.selectedIndex].text; document.getElementById("nome_marca").value = textoSelecionado; var cat = document.getElementById("gre_cat_id").value; var element = document.getElementById("gre_mod_id"); element.innerHTML = ''; // Limpa opções existentes var node = document.createElement("option"); var textnode = document.createTextNode("Selecione"); node.setAttribute("value", ""); node.appendChild(textnode); element.appendChild(node); for (var i = 0; i < obj.length; i++) { // if (obj[i].nivel == nivel && obj[i].tipo_pg == tipo) { if(obj[i].id_cat === cat && obj[i].id_marca === marca) { var node = document.createElement("option"); var textnode = document.createTextNode(obj[i].nome_modelo); node.setAttribute("value", obj[i].id_modelo); node.appendChild(textnode); element.appendChild(node); } } } function pegaProd(modelo) { const select = document.getElementById("gre_mod_id"); const textoSelecionado = select.options[select.selectedIndex].text; document.getElementById("nome_modelo").value = textoSelecionado; var obj = <?php echo json_encode($this->Dados['select']['prod']); ?>; var cat = document.getElementById("gre_cat_id").value; var marca = document.getElementById("gre_marca_id").value; var element = document.getElementById("gre_prod_id"); element.innerHTML = ''; // Limpa opções existentes var node = document.createElement("option"); var textnode = document.createTextNode("Selecione"); node.setAttribute("value", ""); node.appendChild(textnode); element.appendChild(node); for (var i = 0; i < obj.length; i++) { if(obj[i].id_cat === cat && obj[i].id_marca === marca && obj[i].id_modelo === modelo) { var node = document.createElement("option"); var textnode = document.createTextNode(obj[i].nome_prod); node.setAttribute("value", obj[i].id_prod); node.appendChild(textnode); element.appendChild(node); } } } function pegaPreco(prod) { const select = document.getElementById("gre_prod_id"); const textoSelecionado = select.options[select.selectedIndex].text; document.getElementById("nome_produto").value = textoSelecionado; var obj = <?php echo json_encode($this->Dados['select']['prod']); ?>; var cat = document.getElementById("gre_cat_id").value; var marca = document.getElementById("gre_marca_id").value; var modelo = document.getElementById("gre_mod_id").value; for (var i = 0; i < obj.length; i++) { if ( obj[i].id_cat === cat && obj[i].id_marca === marca && obj[i].id_modelo === modelo && obj[i].id_prod === prod ) { // Valor base let precoBase = Number(obj[i].custo_medio); let custo_medio = precoBase.toLocaleString("pt-BR", { minimumFractionDigits: 2, maximumFractionDigits: 2 }); document.getElementById("custo_medio").value = custo_medio; } } } function calculo(){ const temoffice = document.getElementById("gre_cat_id").value; //alert('temoffice: '+temoffice); if (temoffice !== '2') { calculoOffice(); }else{ calculoimpr(); } } function calculoimpr() { alert('aqui será o calculo para impressoras'); } function calcularPrecoPorPrazo(prazoMeses) { const anos = prazoMeses / 12; let simnaoOficce = document.getElementById("office").value || "N"; let simnaoAntivirus = document.getElementById("antivirus").value || "N"; const margem = parseFloat( document.getElementById("perc_margem").value.replace(/[\s%]/g, "").replace(",", ".") ) / 100; const depreciacao = parseFloat( document.getElementById("perc_depreciacao").value.replace(/[%]/g, "").replace(",", ".") ) / 100; const taxaManutencao = parseFloat( document.getElementById("perc_manutencao").value.replace(/[%]/g, "").replace(",", ".") ) / 100; const custo_medio = parseFloat( document.getElementById("custo_medio").value.replace(/\./g, "").replace(",", ".") ); const valorInput = document.getElementById("valor_frete").value; const valorFrete = converterValorBrasileiro(valorInput); //alert('valorFrete'+valorFrete); const valorInputF = document.getElementById("valor_seguro").value; const valorSeguro = converterValorBrasileiro(valorInputF); //alert('valorSeguro'+valorSeguro); const depreciacaoTotal = custo_medio * Math.pow(1 - depreciacao, anos); const manutencaoTotal = custo_medio * taxaManutencao * anos; const manutencaoMensal = Math.round(manutencaoTotal / prazoMeses * 100) / 100; let totalOffice = 0; if (simnaoOficce === "S") { totalOffice = document.getElementById("valor_office").value * anos; } let totalAntivirus = 0; // alert('simnaoAntivirus: '+simnaoAntivirus); if (simnaoAntivirus === "S") { totalAntivirus = document.getElementById("valor_antivirus").value * anos; }else{ totalAntivirus = 0.00; } const custoMensal = custo_medio + totalOffice + totalAntivirus + manutencaoTotal const margemCalc = custoMensal * margem; const preco_com_margem = custoMensal + margemCalc + valorFrete + valorSeguro; const aluguel_mensal = Math.round(preco_com_margem / prazoMeses * 100) / 100; const lucroLiquido = preco_com_margem + depreciacaoTotal - custoMensal; //alert('lucroLiquido: '+lucroLiquido+' custoMensal :'+custoMensal +'valorFrete: '+ valorFrete + ' valorSeguro: '+valorSeguro); const roitempo = Math.round(((lucroLiquido / (custoMensal - manutencaoTotal + valorFrete + valorSeguro ))*100) * 100) / 100; //alert('roi: '+roitempo); return { custo_medio, totalAntivirus, totalOffice, valorSeguro, valorFrete, depreciacaoTotal, manutencaoTotal, custoMensal, precoMensal: aluguel_mensal, lucroLiquido, preco_com_margem, roitempo }; } function calculoOffice() { const select = document.getElementById("gre_prazo_id"); const texto = select.options[select.selectedIndex].text; if (texto === "Selecione") { mostrarAlerta("ERRO", "Prazo de Contrato Obrigatório", "error"); return; } const [prazo1, prazo2, prazo3] = texto.split("/").map(Number); if ([prazo1, prazo2, prazo3].some(isNaN)) { mostrarAlerta("ERRO", "Formato de prazo inválido", "error"); return; } const resultados = [ { prazo: prazo1, label: "lb1", campo: "preco1" }, { prazo: prazo2, label: "lb2", campo: "preco2" }, { prazo: prazo3, label: "lb3", campo: "preco3" }, ]; const calculos = resultados.map(({ prazo, label, campo }) => { const resultado = calcularPrecoPorPrazo(prazo); document.getElementById(label).innerHTML = `Preço ${prazo} meses.....:`; document.getElementById(campo).value = resultado.precoMensal.toLocaleString("pt-BR", { minimumFractionDigits: 2, }); return { prazo, valorEquipamento: resultado.custo_medio, valorAntivirus: resultado.totalAntivirus, valorOffice: resultado.totalOffice, valorSeguro: resultado.valorSeguro, valorFrete: resultado.valorFrete, valorDepreciacao: resultado.depreciacaoTotal, valorManutencao: resultado.manutencaoTotal, valorCiclo: resultado.custoMensal, precoMensal: resultado.precoMensal, lucroLiquido: resultado.lucroLiquido, roi: resultado.roitempo, precoComMargem: resultado.preco_com_margem }; }); // ✅ Preenche os campos ocultos no formulário para todos os prazos calculos.forEach((item, index) => { const i = index + 1; document.getElementById(`valorAntivirus${i}`).value = Number(item.valorAntivirus).toFixed(2); document.getElementById(`valorOffice${i}`).value = Number(item.valorOffice).toFixed(2); document.getElementById(`valorDepreciacao${i}`).value = Number(item.valorDepreciacao).toFixed(2); document.getElementById(`valorManutencao${i}`).value = Number(item.valorManutencao).toFixed(2); document.getElementById(`valorCiclo${i}`).value = Number(item.valorCiclo).toFixed(2); document.getElementById(`precoMensal${i}`).value = Number(item.precoMensal).toFixed(2); document.getElementById(`lucroLiquido${i}`).value = Number(item.lucroLiquido).toFixed(2); }); // 💬 Monta a tabela com os resultados let htmlTabela = ` <table id="tabelaResultados" style="width:100%; border-collapse: collapse;"> <thead> <tr style="background: #f0f0f0;"> <th style="border:1px solid #ccc; padding:8px;">Indicador</th> ${calculos.map(c => `<th style="border:1px solid #ccc; padding:8px; text-align: center;">${c.prazo} meses</th>`).join('')} </tr> </thead> <tbody> ${[ { label: "Equipamento (R$)", campo: "valorEquipamento" }, { label: "Antivírus anual (R$)", campo: "valorAntivirus" }, { label: "Office anual (R$)", campo: "valorOffice" }, { label: "Seguro anual (R$)", campo: "valorSeguro" }, { label: "Frete (R$)", campo: "valorFrete" }, { label: "Depreciação (R$)", campo: "valorDepreciacao" }, { label: "Manutenção (R$)", campo: "valorManutencao" }, { label: "Custo Ciclo (R$)", campo: "valorCiclo" }, { label: "Preço Total (R$)", campo: "precoComMargem" }, { label: "Assinatura (R$)", campo: "precoMensal" }, { label: "Lucro Líquido (R$)", campo: "lucroLiquido" }, { label: "ROI (%)", campo: "roi", format: val => `${val.toFixed(2)}%` } ].map(item => ` <tr> <td style="border:1px solid #ccc; padding:8px;">${item.label}</td> ${calculos.map(c => ` <td style="border:1px solid #ccc; padding:8px; text-align: ${item.campo === "roi" ? "center" : "right"};"> ${item.format ? item.format(c[item.campo]) : c[item.campo].toLocaleString("pt-BR", { minimumFractionDigits: 2 })} </td> `).join('')} </tr> `).join('')} </tbody> </table> `; // 🪄 Exibe a modal com os resultados document.getElementById("conteudoModal").innerHTML = htmlTabela; document.getElementById("modalCalculo").style.display = "flex"; } function exportarParaExcel() { const tabela = document.getElementById("conteudoModal").innerHTML; const estilo = ` <html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta charset="UTF-8"> </head> <body> ${tabela} </body> </html> `; const blob = new Blob([estilo], { type: "application/vnd.ms-excel;charset=utf-8;" }); const link = document.createElement("a"); link.href = URL.createObjectURL(blob); link.download = "tabela_resultados.xls"; document.body.appendChild(link); link.click(); document.body.removeChild(link); } function fecharModal() { document.getElementById("modalCalculo").style.display = "none"; document.getElementById("acao").style.display = 'block'; const campo = document.getElementById("condicoes"); const usuario = "<?php echo isset($_SESSION['form']['gre_prazo_id']) ? $_SESSION['form']['gre_prazo_id'] : ''; ?>"; if (usuario) { document.getElementById("divcond").style.display = 'none'; } else { document.getElementById("divcond").style.display = 'block'; } } function converterValorBrasileiro(valorStr) { if (!valorStr || typeof valorStr !== "string") return 0; // Remove pontos de milhar e substitui vírgula decimal por ponto const valorLimpo = valorStr.replace(/\./g, "").replace(",", "."); const valorNumerico = parseFloat(valorLimpo); // Retorna 0 se não for número válido return isNaN(valorNumerico) ? 0 : valorNumerico; } function aoEnviar(event) { const botao = document.activeElement; if (botao.id === "limpar") { limpaDados(); // chama a função de limpar antes de enviar } return true; // permite o submit continuar } </script>