var Sinisa = Class.extend({
/** seletores jQuery | {fk_campo: '#fk_campo'} **/
_s: {},
_popUp:{},
/** retorna um objeto jQuery via id do seletor **/
s: function (idSeletor) {
if (typeof (this._s[idSeletor]) == 'undefined') {
throw 'Seletor não encontrado: ' + idSeletor;
}
return $(this._s[idSeletor]);
},
init: function () {
this.log('[sinisa.init] Inicializando aplicação');
},
config: function () {
//this._configToastr();
this.stickyMenu();
this._configChosen();
$.blockUI.defaults['message'] = '
Aguarde...
';
},
alert: function (message, callback, iconType) {
if (!iconType) {
iconType = 'info'
}
swal({
type: iconType,
html: message,
closeOnConfirm: true,
allowOutsideClick: false,
imageSize: '60x60'
}, (callback || function () {
}));
},
confirm: function (message, fnConfirm, fnCancel) {
swal({
title: 'Confirme',
html: message,
type: 'warning',
showCancelButton: true,
allowOutsideClick: false,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Sim',
cancelButtonText: 'Não',
confirmButtonClass: 'confirm-class',
cancelButtonClass: 'cancel-class',
}, function (isConfirm) {
if (isConfirm) {
$.isFunction(fnConfirm) && fnConfirm();
} else {
$.isFunction(fnCancel) && fnCancel();
}
});
},
_configToastr: function () {
this.log('[sinisa.config] Configurando o toastr js');
toastr = toastr || {};
toastr.options = {
"closeButton": true,
"debug": false,
"newestOnTop": true,
"progressBar": true,
"positionClass": "toast-top-right",
"preventDuplicates": false,
"onclick": null,
"showDuration": "300",
"hideDuration": "1000",
"timeOut": "5000",
"extendedTimeOut": "1000",
"showEasing": "swing",
"hideEasing": "linear",
"showMethod": "fadeIn",
"hideMethod": "fadeOut"
}
},
_configChosen: function () {
this.log('[sinisa.config] Configurando o Chosen combobox');
$('.chosen-select').each(function (k, v) {
var $chosen = $(v);
$chosen.chosen({
width: $chosen.attr('data-chosen-width') || '100%',
allow_single_deselect: $chosen.attr('data-chosen-allow-single-deselect') || false
});
});
},
log: function (mxMsg, strID, strTipo) {
if (_.isUndefined(console) || !_.isObject(console) || !console) {
return false;
}
strTipo = strTipo || 'log';
if (_.isUndefined(console[strTipo])) {
throw('[sinisa.log] Erro de referência: console.' + strTipo + '()');
}
if (strID) {
console[strTipo](strID + ': ', mxMsg);
} else {
console[strTipo](mxMsg);
}
},
toggleInfo: function (codInfo) {
$('.hint-' + codInfo).toggle('fast', function () {
var $this = $(this);
var isOpened = $this.css('display') != 'none';
if (isOpened) {
$('.btn-info-' + codInfo).find('i')
.removeClass('fa-plus')
.addClass('fa-minus')
;
} else {
$('.btn-info-' + codInfo).find('i')
.removeClass('fa-minus')
.addClass('fa-plus')
;
}
});
},
/**
* função que fixa o menu no topo quando rola o scroll
*/
stickyMenu: function () {
$sticky_nav = $('div#box-cabecalho');
$sticky_header = $('section.content-header');
// não está dentro dos forms da coleta
if ($sticky_nav.length == 0) {
return;
}
$sticky_nav_offset = $sticky_nav.offset();
$sticky_nav_top = $sticky_nav_offset.top;
$sticky_nav_width = $sticky_nav.width();
$sticky_header_offset = $sticky_header.offset();
$sticky_header_top = $sticky_header_offset.top;
var sticky_navigation = function() {
var scroll_top = $(window).scrollTop();
if (scroll_top >= $sticky_header_top - 40) {
$sticky_nav.css({
'background-color' : '#ecf0f5',
'padding-top' : '2px',
'position' : 'fixed',
'top' : '105px',
'width' : $sticky_nav_width,
'z-index' : 299
});
$sticky_header.css({
'background-color' : '#ecf0f5',
'padding-top' : '2px',
'padding-bottom' : '2px',
'position' : 'fixed',
'top' : '50px',
'width' : $sticky_nav_width,
'z-index' : 299
});
}
else {
$sticky_nav.css({
'background-color' : '',
'padding-top' : '0',
'position' : 'relative',
'top' : '0'
});
$sticky_header.css({
'background-color' : '',
'padding-top' : '0',
'padding-bottom' : '0',
'position' : 'relative',
'top' : '0'
});
}
};
sticky_navigation();
$(window).scroll(function() {
sticky_navigation();
});
$(window).resize(function() {
$sticky_nav_width = $('section.content-header').width();
$sticky_nav.css({
'background-color' : '#ecf0f5',
'padding-top' : '2px',
'position' : 'fixed',
'top' : '50px',
'width' : $sticky_nav_width,
'z-index' : 299
});
});
},
maskIt: function (w, e, m, r, a) {
String.prototype.reverse = function () {
return this.split('').reverse().join('');
};
// Cancela se o evento for Backspace
if (!e)
var e = window.event
if (e.keyCode)
code = e.keyCode;
else if (e.which)
code = e.which;
// Variaveis da funcao
var txt = (!r) ? w.value.replace(/[^\d]+/gi, '') : w.value.replace(/[^\d]+/gi, '').reverse();
var mask = (!r) ? m : m.reverse();
var pre = (a) ? a.pre : "";
var pos = (a) ? a.pos : "";
var ret = "";
if (code == 9 || code == 8 || txt.length == mask.replace(/[^#]+/g, '').length)
return false;
// Loop na máscara para aplicar os caracteres
for (var x = 0, y = 0, z = mask.length; x < z && y < txt.length; ) {
if (mask.charAt(x) != '#') {
ret += mask.charAt(x);
x++;
}
else {
ret += txt.charAt(y);
y++;
x++;
}
}
// Retorno da função
ret = (!r) ? ret : ret.reverse()
w.value = pre + ret + pos;
},
showPopupContatos: function (urlPopUp) {
if (typeof (this._popUp["ContatoPsv"]) == 'undefined' || this._popUp.ContatoPsv.closed) {
this._popUp["ContatoPsv"] = window.open(urlPopUp, "ContatoPsv", "height=750,width=1100, scrollbars=yes,statusbar=no,resizable=no,toolbar=0");
}
else {
this._popUp["ContatoPsv"].focus();
}
},
closePopupContatos: function (opner) {
if (typeof (this._popUp["ContatoPsv"]) != 'undefined' && this._popUp.ContatoPsv.closed){
this._popUp["ContatoPsv"].parent.close();
}
else if (opner) {
window.close();
}
},
});/**
* Funções utilitárias de uso geral
*/
Sinisa.prototype.util = new (Sinisa.extend({
jr: function (seletor) {
return $(seletor).val();
},
jw: function (seletor, value) {
$(seletor).val(value);
},
attrId: function (mxObj) {
return Number(this._extractAttrVlr(mxObj)[0]);
},
attrVal: function (mxObj) {
return String(this._extractAttrVlr(mxObj)[1]);
},
/**
* Extrai o par "id@sigla" dos campos que implementam a tabela tab_atributos_valores
* Aceita:
* 1. seletor jQuery. ex: #id | .classe
* 2. objeto jQuery. ex: $('#id')
* 3. objeto html. ex:
* 4. string. ex: '22@DN'
*/
_extractAttrVlr: function (mxObj) {
var r, m, s = '@';
if (!mxObj) return '';
if (_.isString(mxObj)) {
// string
if (mxObj.indexOf(s) > 0) {
r = mxObj.split(s);
}
// seletor jQuery
else if ((s = $(mxObj)).length > 0) {
r = s.val().split(s);
}
else {
throw new Error('[sinisa.util._extractAttrVlr] tipo do objeto "mxObj" não reconhecido como string válida.');
}
}
// objeto jquery $(..)
else if (mxObj instanceof jQuery) {
r = mxObj.val().split(s);
}
// objeto javascript
else if (typeof mxObj == 'object') {
r = $(mxObj).val().split(s);
}
else {
throw new Error('[sinisa.util._extractAttrVlr] tipo do objeto "mxObj" não reconhecido como objeto válido.');
}
return r;
},
retiraFormatoMoeda: function (valor) {
valor = (valor) ? valor.replace(/\./g, "").replace(",", ".") : 0;
return valor;
},
colocaFormatoMoeda: function (n, c, d, t) {
c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
},
scrollTo: function (el, top) {
top = top || 60;
var _el = typeof(el) == 'jQuery' ? el : $("#"+ el);
if (_el.length > 0) {
$("html, body").animate({scrollTop: _el.offset().top - top}, 2000);
}
},
scrollTop: function () {
$("html, body").animate({scrollTop: 0}, 2000);
}
}));/**
* Tratamento de conexões via ajax
*/
Sinisa.prototype.ajax = new (Sinisa.extend({
intContadorReq: 0, // contador de requisições ajax
init: function () {
this.log('[sinisa.ajax] ajax pronto para uso');
},
defaultBlockUI: function(){
$.blockUI();
},
defaultUnblockUI: function(){
$.unblockUI();
},
blockUI: null,
unblockUI: null,
fnAjaxFail: function (jqXhr, textStatus, errorThrown) {
console && console.log('[sinisa.ajax.fail] Falha na requisição [#'+ jqXhr.status +']: ' + errorThrown, null, 'error');
var msg = 'Erro interno';
if (typeof(jqXhr.responseJSON) !== 'undefined' && jqXhr.responseJSON.msg) {
msg = jqXhr.responseJSON.msg;
}
if (typeof(sinisa.ajax.unblockUI) === 'function') {
sinisa.ajax.unblockUI();
sinisa.ajax.unblockUI = null;
}
else {
sinisa.ajax.defaultUnblockUI();
}
sweetAlert('Houve um problema na requisição', msg, 'error');
},
fnAjaxAlways: function (mxDataOrJqXhr, textStatus, jqXhrOrErrorThrown) {
var resposta = {
mxDataOrJqXhr: mxDataOrJqXhr,
textStatus: textStatus,
jqXhrOrErrorThrown: jqXhrOrErrorThrown,
};
if (typeof(sinisa.ajax.unblockUI) === 'function') {
sinisa.ajax.unblockUI();
sinisa.ajax.unblockUI = null;
}
else {
sinisa.ajax.defaultUnblockUI();
}
console && console.log(resposta, '[sinisa.ajax.always] Resposta da requisição ['+
mxDataOrJqXhr.sinisaAjaxIntContadorReq +']');
},
fnAjaxDone: function (data, textStatus, jqXhr) {
if (typeof(sinisa.ajax.unblockUI) === 'function') {
sinisa.ajax.unblockUI();
sinisa.ajax.unblockUI = null;
}
else {
sinisa.ajax.defaultUnblockUI();
}
},
/**
* Requisição genérica
*/
request: function (strUrl, objDados, fnCallback, strTipoRequisicao) {
var me = this;
// function(data) {}
fnCallback = fnCallback || function() {};
// par {chave: valor, ...}
objDados = objDados || {};
// POST | GET | JSON
strTipoRequisicao = strTipoRequisicao || 'POST';
/**
* Yii 2.0 CSRF validation for AJAX request
*/
if ($.inArray(strTipoRequisicao.toUpperCase(), ['GET', 'POST', 'OPTIONS'])) {
var csrfParam = $('meta[name="csrf-param"]').attr("content");
var csrfToken = $('meta[name="csrf-token"]').attr("content");
objDados[csrfParam] = csrfToken;
}
objDados.sinisaAjaxIntContadorReq = ++this.intContadorReq;
var jqXhr = $.ajax({
type: strTipoRequisicao,
url: strUrl,
data: objDados,
success: function(data, textStatus, jqXHR){
if (typeof(sinisa.ajax.unblockUI) === 'function') {
sinisa.ajax.unblockUI();
sinisa.ajax.unblockUI = null;
}
else {
sinisa.ajax.defaultUnblockUI();
}
if (typeof(jqXHR.responseJSON) !== 'undefined' && jqXHR.responseJSON.status == 'undefined') {
$.error('Erro ao receber a resposta da requisição. "status" precisa estar presente na resposta.');
}
else if (typeof(jqXHR.responseJSON) !== 'undefined' && jqXHR.responseJSON.status == 'erro') {
sweetAlert('Houve um problema na requisição', (jqXHR.responseJSON.msg || ''), 'error');
}
else {
fnCallback(data, textStatus, jqXHR);
}
},
cache: false,
async: true,
beforeSend: function(jqXhr) {
if (typeof(sinisa.ajax.blockUI) === 'function') {
sinisa.ajax.blockUI();
sinisa.ajax.blockUI = null;
}
else {
sinisa.ajax.defaultBlockUI();
}
// log das requisições
var ac = this.intContadorReq,
msg = '[sinisa.ajax.request] ['+ ac +'] Requisição Ajax Efetuada: ' + strUrl
;
me.log(objDados || {}, msg);
}
})
.then(function(dataJSON, textStatus, xhr) {
if (strTipoRequisicao == 'POST' || _.isObject(dataJSON)) {
if (dataJSON.status == 'erro') {
return $.Deferred()
.reject(xhr, dataJSON, dataJSON.msg)
.promise();
}
}
return dataJSON;
})
.always(this.fnAjaxAlways)
.fail(this.fnAjaxFail)
.done(this.fnAjaxDone);
return jqXhr;
},
post: function (strUrl, objDados, fnCallback) {
if (_.isFunction(objDados)) {
fnCallback = objDados;
objDados = {};
}
else if (_.isUndefined(objDados)) {
objDados = {};
}
return this.request(strUrl, objDados, fnCallback, 'POST');
},
get: function (strUrl, fnCallback) {
return this.request(strUrl, {}, fnCallback, 'GET');
}
}));
/**
* Classe responsável por gerenciar as ações do glossário
*/
Sinisa.prototype.glossario = new (Sinisa.extend({
/**
* configuração de seletores para facilitar o acesso
* os mesmos podem ser acessados via: this.s(id-seletor)
*/
_s: {
attr_servico: '#tabglossariossearch-fk_attr_servico',
tipo_origem: '#tabglossariossearch-fk_tipo_origem',
bloco_info: '#tabglossariossearch-fk_glossario_bloco_info',
tipo_apresentacao: '#tabglossariossearch-fk_tipo_apresentacao',
bln_obrigatorio: '#tabglossariossearch-bln_obrigatorio',
opt_apresentacao: '#tabglossariossearch-fk_opt_apresentacao',
casas_decimais: '#tabglossariossearch-num_casas_decimais',
vlr_min: '#tabglossariossearch-num_vlr_min',
vlr_max: '#tabglossariossearch-num_vlr_max',
txt_formula_ag: '#tabglossariossearch-txt_formula_ag',
txt_formula_es: '#tabglossariossearch-txt_formula_es',
txt_formula_ae: '#tabglossariossearch-txt_formula_ae',
txt_formula_rs: '#tabglossariossearch-txt_formula_rs',
txt_formula_dn: '#tabglossariossearch-txt_formula_dn',
bln_is_somatorio: '#tabglossariossearch-bln_is_somatorio',
txt_formula_tot: '#tabglossariossearch-txt_formula_tot',
form: '#tabglossariossearch-fk_glossario_form',
txt_info_dado_externo: '#tabglossariossearch-txt_info_dado_externo',
cod_atributo_fk: '#tabglossariossearch-cod_atributo_fk',
dependencia_apresentacao_fk: '#tabglossariossearch-dependencia_apresentacao_fk',
dependencia_glossario_fk : '#tabglossariossearch-dependencia_glossario_fk',
grp_txt_formula_ag: '.field-tabglossariossearch-txt_formula_ag',
grp_txt_formula_es: '.field-tabglossariossearch-txt_formula_es',
grp_txt_formula_ae: '.field-tabglossariossearch-txt_formula_ae',
grp_txt_formula_rs: '.field-tabglossariossearch-txt_formula_rs',
grp_txt_formula_dn: '.field-tabglossariossearch-txt_formula_dn'
},
/**
* retorna o objeto formulário no qual os campos estão associados
*/
$form: function () {
return $(this.s('tipo_origem').parents('form:first'));
},
/**
* método construtor
*/
init: function () {
this.log('[sinisa.glossario] inicializando glossario');
this.tipoOrigemChange();
this.tipoApresentacaoChange();
this.formChange();
this.dependenciaOpcaoChange();
this.dependenciaApresentacaoChange();
this.log('[sinisa.glossario] glossario pronto para uso');
},
/**
* Carrega os blocos do form
*/
formChange: function () {
var $comboBloco = this.s('bloco_info'), $comboForm = this.s('form');
$comboForm.change(function () {
var fkForm = $comboForm.find('option:selected').val();
if (fkForm === '') {
$comboBloco.find('option:not(:first)').remove();
return false;
}
sinisa.ajax.post('drenagem/glossario/get-blocos-by-form', {fk_form: fkForm}, function (blocos) {
$comboBloco.find('option:not(:first)').remove();
$.each(blocos, function () {
$comboBloco.append($('', {
value: this.cod_bloco_info,
text: this.dsc_titulo_bloco
}));
});
$comboBloco.select2('destroy').select2({
allowClear: true,
theme: 'krajee',
width: '100%',
placeholder: '-- selecione --',
language: 'pt-BR'
});
});
});
},
/**
* evento change do campo Tipo de origem
*/
tipoOrigemChange: function () {
var me = this, ori, srv;
var disableAll = function () {
me.s('txt_formula_ag').attr('disabled', true);
me.s('txt_formula_es').attr('disabled', true);
me.s('txt_formula_ae').attr('disabled', true);
me.s('txt_formula_rs').attr('disabled', true);
me.s('txt_formula_dn').attr('disabled', true);
me.s('grp_txt_formula_ag').hide();
me.s('grp_txt_formula_es').hide();
me.s('grp_txt_formula_ae').hide();
me.s('grp_txt_formula_rs').hide();
me.s('grp_txt_formula_dn').hide();
};
disableAll();
me.s('tipo_origem').change(function () {
ori = me.util.attrVal(me.s('tipo_origem')),
srv = me.util.attrVal(me.s('attr_servico'))
if (me.$form().data('yiiActiveForm')) {
me.$form().yiiActiveForm('resetForm');
}
me.s('bln_obrigatorio').attr('disabled', (ori !== 'D'));
me.s('txt_formula_tot').attr('disabled', (ori !== 'T')).parents().first()[ori==='T' ? 'show' : 'hide']('fast');
me.s('txt_info_dado_externo').attr('disabled', (ori !== 'E')).parents().first()[ori==='E' ? 'show' : 'hide']('fast');
// se for [I]ndicador
if (ori == 'I') {
switch (srv) {
case 'AG' :
me.s('grp_txt_formula_ag').show();
me.s('txt_formula_ag').attr('disabled', false);
break;
case 'ES' :
me.s('grp_txt_formula_es').show();
me.s('txt_formula_es').attr('disabled', false);
break;
case 'AE' :
me.s('grp_txt_formula_ae').show();
me.s('txt_formula_ae').attr('disabled', false);
break;
case 'RS' :
me.s('grp_txt_formula_rs').show();
me.s('txt_formula_rs').attr('disabled', false);
break;
case 'DN' :
me.s('grp_txt_formula_dn').show();
me.s('txt_formula_dn').attr('disabled', false);
break;
}
}
else {
disableAll();
}
me.isIndicador = (ori == 'I');
});
me.s('tipo_origem').trigger('change');
},
/**
* evento change do campo Tipo de apresentação
*/
tipoApresentacaoChange: function () {
var me = this;
// [habilita | desabilita] as opções de apresentação
me.s('tipo_apresentacao').change(function () {
var opts = ['checkboxlist', 'dropdownlist', 'multiselect', 'radiolist'],
opt, disabled
;
opt = me.util.attrVal(this);
disabled = !_(opts).includes(opt);
if (disabled && me.$form().data('yiiActiveForm')) {
me.$form().yiiActiveForm('resetForm');
}
me.s('opt_apresentacao').attr('disabled', disabled).trigger("chosen:updated");
})
// opções do campo numérico
me.s('tipo_apresentacao').change(function () {
var disabled = (me.util.attrVal(this) != 'input:numeric' && me.util.attrVal(this) != 'input:money'),
c = ['casas_decimais', 'vlr_min', 'vlr_max']
;
_(c).each(function (item) {
me.s(item).attr('disabled', disabled);
});
});
// dispara o evento para poder realizar as configurações acima
me.s('tipo_apresentacao').trigger('change');
},
/**
* Carrega a apresentação do campo pai
*/
dependenciaApresentacaoChange: function () {
var $campoDependencia = this.s('dependencia_glossario_fk'), $opcaoDependencia = this.s('cod_atributo_fk'), $valorDependencia = this.s('dependencia_apresentacao_fk');
$opcaoDependencia.attr('disabled', true).trigger("chosen:updated");
$valorDependencia.attr('disabled', true).trigger("chosen:updated");
if ($campoDependencia.val()) {
if ($opcaoDependencia.val()) {
$valorDependencia.attr('disabled', false).trigger("chosen:updated");
}
}
$opcaoDependencia.change(function () {
var fkAtributo = $opcaoDependencia.find('option:selected').val();
if (fkAtributo === '' || typeof fkAtributo === "undefined") {
$valorDependencia.find('option:not(:first)').remove();
$valorDependencia.attr('disabled', true).trigger("chosen:updated");
return false;
}
sinisa.ajax.post('drenagem/glossario/get-valor-dependencia', {fk_atributo: fkAtributo}, function (atrValores) {
$valorDependencia.find('option:not(:first)').remove();
$valorDependencia.attr('disabled', false).trigger("chosen:updated");
$.each(atrValores, function () {
$valorDependencia.append($('', {
value: this.cod_atributos_valores,
text: this.dsc_descricao
}));
});
$valorDependencia.select2('destroy').select2({
allowClear: true,
theme: 'krajee',
width: '100%',
placeholder: '-- selecione --',
language: 'pt-BR'
});
});
});
},
/**
* Carrega a apresentação do campo pai
*/
dependenciaOpcaoChange: function () {
var $campoDependencia = this.s('dependencia_glossario_fk'), $opcaoDependencia = this.s('cod_atributo_fk'), $valorDependencia = this.s('dependencia_apresentacao_fk');
$campoDependencia.change(function () {
var fkAtributo = $(this).find('option:selected').val();
if (fkAtributo === '') {
$('#tabglossariossearch-cod_atributo_fk').attr('disabled', true).trigger("chosen:updated");
$("#tabglossariossearch-cod_atributo_fk").select2("val", "");
$("#tabglossariossearch-dependencia_apresentacao_fk").select2("val", "");
//$('#tabglossariossearch-dependencia_apresentacao_fk').attr('disabled', true).trigger("chosen:updated");
return false;
} else {
//, $comboForm = this.s('cod_atributo_fk');
sinisa.ajax.post('drenagem/glossario/get-opcao-dependencia', {fk_atributo: fkAtributo}, function (atrValores) {
$valorDependencia.find('option:not(:first)').remove();
$valorDependencia.attr('disabled', false).trigger("chosen:updated");
$opcaoDependencia.val(atrValores.fk_opt_apresentacao).trigger("change");
});
}
});
},
}));sinisa = new Sinisa();sinisa.config();