Synchronize an automated Dataset

Asked

Viewed 441 times

-1

Good morning! I’m creating a sicronized dataset inside a Totvs system called Fluig, I can get that dataset to search my database and return the information quietly, but when I put for it to do this operation automatically at least once a day appears the following error:

sun.org.Mozilla.javascript.Internal.Ecmaerror: Referenceerror: "consultHCM" is not defined. (#23) in at line number 23

Could someone help me? NOTE: the database is the Senior HCM

function defineStructure()
{
addColumn("NOME");
addColumn("SETOR");
addColumn("EMAIL");
setKey(["NOME"]);
addIndex(["NOME"]);
}

function onSync(lastSyncDate)
{
var today = new Date();

var funcionarios = new Array();

var dataset = DatasetBuilder.newDataset();

var fields = new Array();

fields.push("NOME");
fields.push("SETOR");
fields.push("EMAIL");

//Linha 93
funcionarios = consultaHCM();

var number = funcionarios.length;

for(var i=0; i<funcionarios.length; i++)
{
    var separador = funcionarios[i].split(";");
    var nome = separador[0];
    var setor = separador[1];
    var email = separador [2];


    dataset.addOrUpdateRow(new Array(nome, setor));

    if(consultaCadastroRepetido(nome, setor))
    {
        //NÃO CRIA REGISTRO
        log.info("CADASTRO REPETIDO");
    }
        else
        {
            //CRIAR REGISTRO
            //Linha 193
            iniciaSolicitacaoCadastro(nome,setor);
        }
    }   

return dataset;
}

function createDataset(fields, constraints, sortFields) {
  var dataset = DatasetBuilder.newDataset();

    try{
                        //ESCOLHE O BANCO DE DADOS
        var dataSource = "jdbc/JDBC_Folha_Oracle";
      //  var orderBy = " ORDER BY fun.NomFun ";
        var orderBy = " ORDER BY fun.NumCad ";

        var ic = new javax.naming.InitialContext();
        var ds = ic.lookup(dataSource);    
        var conn = ds.getConnection();
        var stmt = conn.createStatement();
        var created = false;

        var myQuery = " SELECT fun.NumEmp AS NUMEMP , CONCAT(fun.NumCad , concat (' - ', fun.NomFun)) AS COD_NOME, fun.NumCad AS NUMCAD , fun.NomFun AS NOMFUN, fun.SitAfa AS SITAFA, car.CODCAR, car.TitCar AS TITCAR, fun.CodFil AS CODFIL \
         FROM R034FUN fun , R024CAR car WHERE fun.SitAfa NOT IN ( 7,17 ) AND fun.TipCol = 1 AND fun.EstCar = car.EstCar AND fun.CodCar = car.CodCar ";

        if (constraints != null) {
            for (i in constraints) {
                var opeLogicos = " AND ";
                if (constraints[i].getConstraintType() == "MUST" || constraints[i].getConstraintType() == "MUST_NOT")
                    opeLogicos = " AND ";
                else if (constraints[i].getConstraintType() == "SHOULD")
                    opeLogicos = " OR ";

                var operadores = "";
                if (constraints[i].getConstraintType() == "MUST")
                    operadores = " = ";
                else if (constraints[i].getConstraintType() == "SHOULD")
                    operadores = " LIKE ";
                else if (constraints[i].getConstraintType() == "MUST_NOT")
                    operadores = " <> ";

                if (i == 0)
                    myQuery += " AND ";
                else {
                    myQuery += opeLogicos == "" ? "" : opeLogicos;
                }
                if( constraints[i].getFieldName() == 'sqlLimit' ){
                    myQuery += " ROWNUM <= '" + constraints[i].getInitialValue() + "'";
                }else
                    myQuery += constraints[i].getFieldName() + operadores + " '" + constraints[i].getInitialValue() + "'";

            }
        }
        myQuery = myQuery + orderBy;
        log.info("DataSet R034FUN myQuery " + myQuery );
        var rs = stmt.executeQuery(myQuery);

        var columnCount = rs.getMetaData().getColumnCount();
        while (rs.next()) {
            if (!created) {
                for (var i = 1; i <= columnCount; i++) {
                    dataset.addColumn(rs.getMetaData().getColumnName(i));
                }
                created = true;
            }
            var Arr = new Array();
            for (var i = 1; i <= columnCount; i++) {
                var obj = rs.getObject(i);
                if (null != obj) {
                    Arr[i - 1] = rs.getObject(i).toString();
                } else {
                    Arr[i - 1] = "";
                }
            }
            dataset.addRow(Arr);
        }

    } catch (e) {
        log.error("ERRO DataSet R034FUN ============> " + e.message);

    }finally{
        if (stmt != null) {
            stmt.close();
        }
        if (conn != null) {
            conn.close();
        }
    }

    return dataset;


function onMobileSync(user)
{

}

function consultaHCM()
{
var NOME_SERVICO = "WsConsultaSQL";
var CAMINHO_SERVICO = "com.totvs.WsConsultaSQL";

var funcionarios = new Array();

try {  
    var servico = ServiceManager.getServiceInstance(NOME_SERVICO);          
    var instancia = servico.instantiate(CAMINHO_SERVICO);          
    var ws = instancia.getRMIwsConsultaSQL();            
    var serviceHelper = servico.getBean();  
    var authService = serviceHelper.getBasicAuthenticatedClient(ws, "com.totvs.IwsConsultaSQL", 'LOGIN', 'SENHA');  

    /** 
     * O método realizarConsultaSQL espera 4 parametros: 
     * 1º - Código da Consulta SQL cadastrada no sistema 
     * 2º - Código da Coligada 
     * 3º - Código do Sistema 
     * 4º - Parametros utilizados na consulta SQL. Ex.: "CODCOLIGADA=1;UF=MG" 
     * Retorno: Um XML de um DataTable do retorno da execução da consulta SQL
     */  

    var result = authService.realizarConsultaSQL("SQL.FLUIG.006", 1, "P", "1=1");  
     if ((result != null) && (result.indexOf("===") != -1)) {  
        var msgErro = result.substring(0, result.indexOf("==="));  
        log.error("Erro: " + msgErro);  
        throw "Erro: " + msgErro;  
     }  

    var xmlResultados = new XML(result);    

    for(var j = 0; j < xmlResultados.Resultado.length(); j++)
    {
        funcionarios[j] = xmlResultados.Resultado[j].NOME.toString() + ";" + xmlResultados.Resultado[j].DESCRICAO.toString() + ";" + xmlResultados.Resultado[j].INICPROGFERIAS1.toString() + ";" + xmlResultados.Resultado[j].FIMPROGFERIAS1.toString();
    }            
} 

catch (e) 
{  
     if (e == null)  
         e = "Erro desconhecido; verifique o log do AppServer";  
     var mensagemErro = "Erro na comunicação com o app (linha: " + e.lineNumber + "): " + e;  
     log.error(mensagemErro);  
}   

return funcionarios;

}

function consultaRegistroForm(nome, setor)
{
//CONSULTA SE JÁ EXISTE CADASTRO COM O NOME DO FUNCIONARIO

var c1 = DatasetFactory.createConstraint('nomeFuncionario', nome, nome, ConstraintType.MUST);

for(var i=0;i<c1.rowsCount;i++)
{
    var nomeDs = c1.getValue(i, "nomeFuncionario");

    if(nome == nomeDs)
    {
        //Já existe cadastro do funcionario

        var ultimoCadastro = c1.getValue(i, "nomeFuncionario");

        if(verificaExisteCadastro(nome, setor))
        {
            return false;
        }
        else
        {
            return true;
        }
    }
}

return false;
}


// Se o novo cadastro no HCM ainda não existe no fluig essa função irá criar

function iniciaSolicitacaoCadastro(nome, setor)
{
//CRIAR SOLICITAÇÃO
var login = "login";
var senha = "senha";
var idResponsavel = "fluigadmin"
var solics = "";

try
{
    var workflow = ServiceManager.getService("wsWorkflowEngineService"); 
    var serviceHelper = workflow.getBean(); 

    var serviceLocator = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.ECMWorkflowEngineServiceService"); 

    var service = serviceLocator.getWorkflowEngineServicePort(); 

    var resultArr = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.KeyValueDtoArray");

    var x = 0;
    var field = new Array();

    var formDescritor = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.KeyValueDto");

    var descricao = "Solicitação de teste";
    formDescritor.setKey("formDescritor"); 
    formDescritor.setValue(descricao);
    resultArr.getItem().add(formDescritor);

    field[x] = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.KeyValueDto");
    field[x].setKey("nomeFuncionario");
    field[x].setValue(nome);
    resultArr.getItem().add(field[x]);

    field[x] = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.KeyValueDto");
    field[x].setKey("setor");
    field[x].setValue(setor);
    resultArr.getItem().add(field[x]);

    field[x] = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.KeyValueDto");
    field[x].setKey("emailFuncionario");
    field[x].setValue(email);
    resultArr.getItem().add(field[x]);

    var userArray = serviceHelper.instantiate("net.java.dev.jaxb.array.StringArray");
    userArray.getItem().add("Pool:Group:NPD");

    var processAttachmentDtoArray = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.ProcessAttachmentDtoArray");
    var appointment = serviceHelper.instantiate("com.totvs.technology.ecm.workflow.ws.ProcessTaskAppointmentDtoArray");

    var ret = service.startProcessClassic(login, senha, 1, "testehcm", 5, userArray, "", idResponsavel, true, processAttachmentDtoArray, resultArr, appointment, false);
}
catch (e)
{
    log.error("######### "+e);
}
}


function consultaRegistroRepetido(nome, setor)
{

var c1 = DatasetFactory.createConstraint('nomeFuncionario', nome, nome, ConstraintType.MUST);


for(var i=0;i<ds.rowsCount;i++)
{
    return true;
}

return false;
}
}

1 answer

0

Your function query HCM is inside the createDataset, so onSync cannot order it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.