从HTMLService Template调用google.script.run

时间:2017-09-25 17:44:19

标签: web-services google-apps-script google-sheets

当我尝试执行命令

  

var obj = google.script.run.receitaws(cnpj);

来自自定义html模板表单的

不起作用,返回Undefined,但是当通过电子表格工作运行此函数时。

我将在下面发布我的项目:

我结合了许多html文件来创建html struture表单。

要加入文件,请使用 include(文件)

功能
function include(File) {
  var template = HtmlService.createTemplateFromFile(File).evaluate();
  Logger.log(template.getContent());
  return HtmlService.createHtmlOutput(template.getContent()).getContent();
}

按功能 openlink

调用我的自定义html模板
function openlink() {
  var template = HtmlService.createTemplateFromFile('tabs')
                    .evaluate()
                    .setSandboxMode(HtmlService.SandboxMode.IFRAME)
                    .setWidth(650);

    SpreadsheetApp.getUi() // Or DocumentApp or FormApp.
      .showModalDialog(template, 'Form');
}

文件标签是一个html模板文件

<?!= include('before')?>

  <ul id="tabs-form-servico" class="tabs">
    <li id="tbulli1" class="tab col s2"><a class="" href="#tab1">1 - Tomador do Serviço</a></li>
    <li id="tbulli2" class="tab col s2"><a class="active" href="#tab2">2 - Prestador do Serviço</a></li>
    <li id="tbulli3" class="tab col s2 hide"><a href="#tab3">3 - Serviço Executado</a></li>
    <li id="tbulli4" class="tab col s2 hide"><a href="#tab4">4 - Regras Retenção Municipal</a></li>
    <li id="tbulli5" class="tab col s2 hide"><a href="#tab5">5 - Regras Retenção Previdenciario</a></li>
    <li id="tbulli6" class="tab col s2 hide"><a href="#tab6">6 - Regras Retenções Federal</a></li>
    <li id="tbulli7" class="tab col s2 hide"><a href="#tab7">7 - Cálculo Retenções</a></li>
    <li id="tbulli8" class="tab col s2 hide"><a href="#tab8">8 - Pagamento</a></li>
  </ul>
  <div id="tab1" class="col s12">Criar</div>
  <div id="tab2" class="col s12"><?!= include('prestadorservico')?></div>
  <div id="tab3" class="col s12">Teste bem sucedido</div>
  <div id="tab4" class="col s12"></div>
  <div id="tab5" class="col s12"></div>
  <div id="tab6" class="col s12"></div>
  <div id="tab7" class="col s12"></div>
  <div id="tab8" class="col s12"></div>

  <script>
    $(document).ready(function(){
      $('#tabs-form-servico').tabs({'swipeable': true });
      Materialize.updateTextFields();
    });

    function close() {
      google.script.host.close()'
    }


  </script>

<?!= include('after')?>

文件之前是html模板文件

<!DOCTYPE html>
<html>
  <head>
    <base target="_blank">
      <!--Import Google Icon Font-->
      <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
      <!--Import materialize.css-->
      <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css" media="screen,projection">

      <!--Let browser know website is optimized for mobile-->
      <meta name="viewport" content="width=device-width, initial-scale=1.0"/>    

  </head>
  <body>

之后的文件是html模板文件

    <script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/js/materialize.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.10/jquery.mask.min.js"> </script>
    <script>

      $(document).ready(function() {
        $('select').material_select();
        $('.tooltipped').tooltip({delay: 50});
      });

    </script>
  </body>
</html>

问题在于html模板文件 prestadorservico

<div class="row">
    <form class="col s12">
      <div class="row">
        <div class="input-field col s3">
          <input  id="cnpj" type="text" class="validate" autofocus>
          <label for="cnpj">CNPJ</label>
        </div>
        <div class="input-field col s1">
          <a class="btn-floating tooltipped rounded" onclick="consultacnpj()" data-tooltip="Preenchimento Automático da RF"><i class="material-icons">refresh</i></a>
        </div>
        <div class="input-field col s8">
          <input placeholder="Prestador LTDA" id="contratado_nome" type="text" class="validate">
          <label for="contratado_nome">Nome do Contratado</label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s10">
          <input value="" id="address" type="text" class="validate">
          <label for="address">Endereço</label>
        </div>
        <div class="input-field col s2">
          <input value="" id="number" type="text" class="validate">
          <label for="number">Número</label>
        </div>        
      </div>
      <div class="row">
        <div class="input-field col s6">
          <input value="" id="compl" type="text" class="validate">
          <label for="compl">Complemento</label>
        </div>
        <div class="input-field col s6">
          <input value="" id="bairro" type="text" class="validate">
          <label for="bairro">Bairro</label>
        </div>        
      </div>
      <div class="row">
        <div class="input-field col s6">
          <?!= include('cidades');?>
        </div>
        <div class="input-field col s6">
          <input value="" id="cep" type="text" class="validate">
          <label for="cep">CEP</label>
        </div>        
      </div>      
      <div class="row">
        <div class="input-field col s7">
          <input id="email" type="email" class="validate">
          <label for="email" data-error="wrong" data-success="right">Email</label>
        </div>
        <div class="input-field col s5">
          <input id="phone" type="text" class="validate">
          <label for="phone">Telefone</label>
        </div>
      </div>
      <div class="row">
        <div class="input-field col s12 m6">
          <input value="" id="cnaep" type="text" class="validate">
          <label for="cnaep">CNAE Principal</label>
        </div>
        <div class="input-field col s12 m6">
          <input value="" id="cnaes" type="text" class="validate">
          <label for="cnaes">CNAE Secundários</label>
        </div>        
      </div>
      <div class="row">
        <div class="input-field col s6">
          <select>
            <option value="" disabled selected>Escolha sua opção</option>
            <option value="1">Pessoa Física</option>
            <option value="2">MEI - Micro Empreendedor Individual</option>
            <option value="3">Imunes/Isentas</option>
            <option value="4">Cooperativa de Trabalho</option>
            <option value="5">Simples Nacional</option>
            <option value="6">Lucro Real/Presumido</option>        
          </select>
          <label>Regime Tributário</label>
        </div>
        <div class="container col s3 offset-s3">
          <a class="btn-large waves-effect waves-light right" id="btnnext2" onclick="nextstep()" name="next">Next
            <i class="material-icons right">send</i>
          </a>
        </div>

       </div> 
    </form>
  </div>
  <div class="divider"> </div>
  <?!= include('SimplesReceitaFederal')?>

  <script>
    function nextstep() {
      $('#tbulli3').removeClass('hide');
      $('#tabs-form-servico').tabs('select_tab', 'tab3');
    }
    function consultacnpj(){
      var cnpj = $('#cnpj').val().toString();
      if (cnpj.length==14){

        var obj = google.script.run.receitaws(cnpj); //here i have a problem
        $('#contratado_nome').val(obj);
        $('#address').val(obj.logradouro);
        $('#number').val(obj.numero);
        $('#compl').val(obj.complemento);
        $('#bairro').val(obj.bairro);
        $('#cep').val(obj.cep);
        $('#city').val((obj.municipio + '/' + obj.uf))
        var code = google.script.run.codeCNAE(obj.atividade_principal[0].code);
        $('#cnaep').val((code + ' - ' + obj.atividade_principal[0].text));
        var codes = google.script.run.CNAESecundarios(obj.atividades_secundarias);
        $('#cnaes').val(codes); 
      } else {
        Materialize.toast('Preencha um CNPJ valido.', 3000)
      }
    }


  </script>

文件 cidades 是一个html模板文件

<? var data = SpreadsheetApp
    .openById('my_id_Sheet')
    .getSheetByName('Municipios')
    .getRange(3, 4, 5575)
    .getValues(); ?>
    <select>
      <option value="" disabled selected>Escolha a Cidade/UF</option>    
      <? for (var i = 0; i < data.length; i++) { ?>
      <option value="<?!= i ?>"><?!= data[i] ?></option>
      <? } ?>
    </select>
    <label>Cidade/UF</label>

Function.gs codeCNAE()

function codeCNAE(cod){
  cod = cod.replace('.', '');
  var cods = cod.split('-');
  cod = cods[0]+'-'+cods[1]+'/'+cods[2];
  return cod;
}

Function.gs CNAESecundarios()

function CNAESecundarios(obj){
  var i, codes = "";
  for (i in obj) {
    if (codes == '') {
      codes = '{' + codeCNAE(obj[i].code)
    } else {
      codes = codes + ', ' + codeCNAE(obj[i].code)
    }
    codes = codes + ' - ' + obj[i].text
  }
  codes = codes + '}'
  //Logger.log(codes);
  return codes;
}

Function.gs receitaws()

function receitaws(cnpj) {
  Utilities.sleep(Math.random() * 1000);
  var token = "my_id_token";
  var url, response, obj;

  url = 'http://receitaws.com.br/v1/cnpj/'
  + cnpj;
  response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true});
  obj = JSON.parse(response);  

  if (obj.status == "ERROR" && obj.message !="CNPJ inválido") {
    Logger.log('Versão Paga');
    url = 'https://receitaws.com.br/v1/cnpj/'
      + cnpj
      + "/days/0";
    response = UrlFetchApp.fetch(url, {'muteHttpExceptions': true, 'headers': {'Authorization': 'Bearer ' + token}});
    obj = JSON.parse(response);
  }
  return obj;    
}

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。在这种情况下,我需要运行

$largeNumberThatBreaksInteger = 10000000000000000000165;
$modulus = $largeNumberThatBreaksInteger / PHP_INT_MAX - (int)($largeNumberThatBreaksInteger / PHP_INT_MAX) * PHP_INT_MAX;
// results in something like -9.9981352879506E+21. So you can compare it with an epsilon and know if it's 0 or not.

获取一个名为的函数返回。

我尝试了这个并且它有效。 我在文件 .withSuccessHandler(onSuccess)

中更改了我的功能 consultacnpj()
prestadorservico

如果有人有其他提示,请发布。 我还在学习google-apps-script和javascript。 谢谢!