/* * Funciones javascript de Verifarma * Version: 3.4 * Fecha: 2014-02-27 */ var version_funciones = '3.4'; // Get the HTTP Object var sorter = null; function getHTTPObject(){ if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP"); else if (window.XMLHttpRequest) return new XMLHttpRequest(); else { alert("Your browser does not support AJAX."); return null; } } function limpiaDivs(elemento){ var diva = document.getElementById(elemento); diva.innerHTML = ' '; } /* * Hace una llamada AJAX */ function doWork(urlAjax, varData, elemento_dst){ cargando(elemento_dst); $.ajax({ type: "POST", url: urlAjax, cache: false, data: varData, success: function(msg) { $('#'+elemento_dst).html(msg); } }); return ""; } function cargando(obj){ $('#'+obj).html('

'); } function parseDataGrafica(texto){ var strStartMatch=new String("|INIDATA|"); var strEndMatch=new String("|FINDATA|"); var intStart=texto.indexOf(strStartMatch, 0) var intEnd=texto.indexOf(strEndMatch, intStart); var rta = texto.substring(intStart+9, intEnd); return rta; } function redirect(location){ document.location.href=location; } function grabaListado(){ // obtengo dato de hidden con listado var diva = document.getElementById('arre_resul'); //grabo cookie SetCookie('arre_result',diva.value + "|" + getCookie('arre_result'),1); alert('Guardada'); } function SetCookie(cookieName,cookieValue,nDays) { var today = new Date(); var expire = new Date(); if (nDays==null || nDays==0) nDays=1; expire.setTime(today.getTime() + 3600000*24*nDays); document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString(); } function getCookie(c_name) { if (document.cookie.length>0) { c_start=document.cookie.indexOf(c_name + "="); if (c_start!=-1) { c_start=c_start + c_name.length+1; c_end=document.cookie.indexOf(";",c_start); if (c_end==-1) c_end=document.cookie.length; return unescape(document.cookie.substring(c_start,c_end)); } } return ""; } function fnCreateSelect( aData ){ var r=''; } /* * Para login */ function getAvailablesVips(){ var username = $("input[name=txtuser]").val(); var pass = $("input[name=txtpassword]").val(); if(username!='' && pass!=''){ $.ajax({ type: "POST", url: '/modulos/general/login', cache: false, data: "txtuser="+username+"&txtpassword="+pass+"&txtvipcode=getvip", success: function(msg) { if(msg!=''){ $('.trvipcode').remove(); var re = jQuery.parseJSON(msg); var vipSelect = 'Credencial ID'; //vipSelect = ''; //vipSelect += ''; vipSelect += ''; $('#trsecid').before(vipSelect); } } } }); } } /**************************************/ function fnFormatDetails (oTab, nTr, urlAjax){ var iIndex = oTab.fnGetPosition( nTr ); var aData = oTab.fnSettings().aoData[iIndex]._aData; var pos = aData.length-1; $.ajax({ type: "POST", url: urlAjax, cache: false, data: aData[pos].replace(/\|/g,"&").replace(/\+/g,"%2B"), success: function(msg) { oTab.fnOpen( nTr, msg, 'apertura'); try{ onLoad(); } catch(e) { } } }); return ""; } function clickPrimero(ii,tabla,url,clase){ // recorre y cierra todas var dondeclick = ii; $('#'+tabla+' tbody td img').each( function () { if (this.src.match('details_close') && dondeclick!= this){ var nTra = this.parentNode.parentNode; this.src = URL_IMG_THEME+"details_open.png"; oTable[tabla].fnClose( nTra ); } } ); if(clase != undefined) { $('.'+clase+' tbody td img').each( function () { if (this.src.match('details_close') && dondeclick!= this){ var nTra = this.parentNode.parentNode; var table_id = this.parentNode.parentNode.parentNode.parentNode.id; this.src = URL_IMG_THEME+"details_open.png"; oTable[table_id].fnClose( nTra ); } }); } var nTr = ii.parentNode.parentNode; //alert(nTr); if (ii.src.match('details_close')){ ii.src = URL_IMG_THEME+"details_open.png"; oTable[tabla].fnClose(nTr); } else{ ii.src = URL_IMG_THEME+"details_close.png"; fnFormatDetails(oTable[tabla], nTr, url); } } var oTable = new Array(); var memfilter=""; var tipoSort = 0; function detectColumnType(data) { if (/^\d+(\.\d+)?$/.test(data)) { return 'number'; } else if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(data)) { return 'date'; } else { return 'string'; } } function iniciarTablas(tabla,offset,paginado){ if(paginado==0){ paginado = false; }else{ paginado = true; } if(TABLE_SIZE==undefined) TABLE_SIZE = 30; jQuery.fn.dataTableExt.oPagination.iFullNumbersShowPages = 3; jQuery.extend(jQuery.fn.dataTableExt.oSort, { "custom-sort-pre": function (data) { if (/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(data)){ var parts = data.split('/'); return Date.parse(parts[2] + '-' + parts[1] + '-' + parts[0]) || 0; } else if (/^[0-9]+$/.test(data)) { return parseInt(data, 10); } return data.toLowerCase ? data.toLowerCase() : data; }, "custom-sort-asc": function (a, b) { return a < b ? -1 : a > b ? 1 : 0; }, "custom-sort-desc": function (a, b) { return a < b ? 1 : a > b ? -1 : 0; } }); oTable[tabla] = $('#'+tabla).dataTable({ "oLanguage": { "sUrl": "/js/dataTables-spanish-txt" }, "ordering":true, "columnDefs": [ { aTargets: [ '_all' ], bSortable: true }], "aoColumnDefs": [ { "sType": "custom-sort", "aTargets": ["_all"], "mRender": function(data, type, full) { var type = detectColumnType(data); if (type === 'date') { var dateObj = new Date(data); var day = dateObj.getDate(); var month = dateObj.getMonth() + 1; var year = dateObj.getFullYear(); return (day < 10 ? '0' + day : day) + '/' + (month < 10 ? '0' + month : month) + '/' + year; } return data; } } ], "bJQueryUI": true, "sPaginationType": 'full_numbers', "bPaginate": paginado, "bInfo": paginado, "sDom": 'T<"clear">lrtip', "iDisplayLength": TABLE_SIZE, "bLengthChange": false, "fnDrawCallback": function () { if ( tabla == 'loteList' ) { var screenWidth = $( 'body' ).width(); var width = $( '#' + tabla + ' thead tr').width() + 115; if( screenWidth < width ){ $( 'body' ).width( width ); } } } } ); /* Add a select menu for each TH element in the table footer */ $('#'+tabla+' tfoot th').each( function (i) { oTable[tabla].fnGetColumnData(i+offset).forEach( function ( d, j ) { if(isNumberValue(d)){ tipoSort = 1; return; } else if(d.includes("/",2) && d.includes("/",5)){ tipoSort = 2; return; } else { tipoSort = 3; return; } } ); if(tipoSort == 1){ $(this).html(fnCreateSelect( oTable[tabla].fnGetColumnData(i+offset).sort(function(a,b){return a-b;}))); }else if(tipoSort == 2){ $(this).html(fnCreateSelect( oTable[tabla].fnGetColumnData(i+offset))); }else{ $(this).html(fnCreateSelect( oTable[tabla].fnGetColumnData(i+offset).sort(function(a,b){ if (a > b) return 1; if (a < b) return -1; return 0;}))); } $('#'+tabla+' select').change( function () { if(memfilter!=$(this).val()){ oTable[tabla].fnFilter( $(this).val(), i+offset ); memfilter = $(this).val(); } }); }); } function iniciarTablaSmall(tabla,offset){ oTable[tabla] = $('#'+tabla).dataTable({ "oLanguage": { "sUrl": "/js/dataTables-spanish-txt" }, "bJQueryUI": true, "bPaginate": false, "bInfo": false, "sDom": 'T<"clear">lrtip', "bSort": false, "iDisplayLength": 20, "bLengthChange": false } ); } function ejecutarSt (ii , urlAjax, fnCallBack, removeTr = false){ var nTable = $(ii).parent().parent().parent().parent().attr("id"); var nTr = ii.parentNode.parentNode; var iIndex = oTable[nTable].fnGetPosition( nTr ); var aData = oTable[nTable].fnSettings().aoData[iIndex]._aData; var pos = aData.length-1; $.ajax({ type: "POST", url: urlAjax, cache: false, async: false, data: aData[pos].replace(/\|/g,"&"), success: function(msg) { if(removeTr){ nTr.remove(); } fnCallBack(msg,ii); } }); return ""; } function actualizaData (ii, datos){ var nTable = $(ii).parent().parent().parent().parent().attr("id"); var nTr = ii.parentNode.parentNode; var iIndex = oTable[nTable].fnGetPosition( nTr ); var aData = oTable[nTable].fnSettings().aoData[iIndex]._aData; var pos = aData.length-1; oTable[nTable].fnSettings().aoData[iIndex]._aData[pos] = datos; } function chk_todo(cch){ if($("#chk_todos,.master_"+cch).is(':checked')){ $("."+cch).each(function(){ if(!$(this).is(':disabled')){ $(this).attr("checked", true); } }); }else{ $("."+cch).attr("checked", false); } } /* * Mensajes de alertas y confirmacion */ // inicia el div que tendra el dialog function iniciaAlerts(al){ al.dialog({ modal: true, autoOpen: false, title: "Verifarma", resizable: false, draggable: false, buttons: [{text: "OK", click: function(e) { $(this).dialog("close"); e.stopPropagation();}}] }); } function iniciarHelp() { $("#helpModal").dialog({ modal: true, autoOpen: false, title: "Verifarma", resizable: false, draggable: true, width:'550px', //height:'500px', buttons: [{text: "OK", click: function(e) { $(this).dialog("close"); e.stopPropagation();}}] }); } function showHelp(htmlText){ $("#helpModal").dialog("option", "buttons", [{text: "OK", click: function(e) { $(this).dialog("close"); e.stopPropagation();}}]); $("#helpModal").dialog("option", "close", function(){ if(foco) { $('#'+foco).focus(); } }); $("#helpModal").dialog("option", "closeOnEscape", true ); $("#helpModal").html(htmlText); $("#helpModal").dialog('open'); } function aviso_hh(tipo,title,msg,foco,callback,cancelar){ alert($("
").html(msg).text()); if(callback!='' && callback!=undefined){ callback(); } } function aviso(tipo,title,msg,foco,callback,cancelar){ var av_texto1 = "Press ESC to continue"; var av_texto2 = "Cancel"; var imagen = 'alert.png'; if(typeof AVISO_ENTER_DISABLED === 'undefined'){ //var AVISO_ENTER_DISABLED = false; } callback = callback || ''; foco = foco || ''; cancelar = cancelar || ''; if(title!=''){ $("#alerts").dialog("option", "title", title); } if(cancelar!=''){ $("#alerts").dialog("option", "buttons", [{text: "OK", click: function(e) { if(callback!='' && callback!=undefined){ $("#alerts").dialog("option", "close", callback); } $(this).dialog("close"); e.stopPropagation();}}, {text: av_texto2, click:function(e){$(this).dialog("option", "close", function(){}); $(this).dialog("close"); eval(cancelar);} }]); $("#alerts").dialog("option", "closeOnEscape", false ); $("#alerts").dialog("option", "close", function(){eval(cancelar);}); }else{ if(AVISO_ENTER_DISABLED && (tipo=='AL' || tipo=='ER')){ $("#alerts").dialog("option", "buttons", ""); }else{ $("#alerts").dialog("option", "buttons", [{text: "OK", click: function(e) { $(this).dialog("close"); e.stopPropagation();}}]); } if(callback!='' && callback!=undefined){ $("#alerts").dialog("option", "close", callback); }else if (foco!=''){ $("#alerts").dialog("option", "close", function(){ $('#'+foco).focus(); }); }else{ $("#alerts").dialog("option", "close", function(){}); } $("#alerts").dialog( "option", "closeOnEscape", true ); } if(msg!=''){ $("#alerts p").html(msg); } switch(tipo){ case 'AL': imagen = "alert.png"; break; case 'OK': imagen = "okbig.png"; break; case 'ER': imagen = "error.png"; break; case 'BL': imagen = "blank_icono.png"; break; case 'IN': imagen = "info.png"; break; case 'PR': imagen = "pregunta.png"; break; case 'OP': imagen = "okproceso.png"; break; } $("#alerts img:first").attr("src",URL_IMG_THEME+imagen); $("#alerts").dialog('open'); if(tipo=='AL' || tipo=='ER'){ if(AVISO_ENTER_DISABLED && cancelar==''){ $("#alerts p").append('

'+av_texto1+''); } $("#error_audio_cf")[0].play(); try{ $("#error_audio_ie")[0].play(); }catch(e){ } } } // Abre un iframe function cuil_cuit(genero, documento){ if(genero=='M') { var AB = '20'; } else if(genero=='F') { var AB = '27'; } else { var AB = '30'; } var multiplicadores = new Array('3', '2', '7','6', '5', '4', '3', '2'); var calculo = ((parseInt(AB.charAt(0))*5)+(parseInt(AB.charAt(1))*4)); for(var i=0;i<8;i++) { calculo += (parseInt(documento.charAt(i))*parseInt(multiplicadores[i])); } var resto = (parseInt(calculo))%11; if((genero!='sociedad')&&(resto<=1)){ if(resto==0){ var C = '0'; } else { if(genero=='hombre'){ var C = '9'; } else { var C = '4'; } } AB = '23'; } else { var C = 11-resto; } var cuil_cuit = AB+"-"+documento+"-"+C; return cuil_cuit; } function openIFrame(link){ var oif_texto1 = "Print"; $.browser.chrome = /chrome/.test(navigator.userAgent.toLowerCase()); $("#iFrame").dialog({ modal: true, autoOpen: false, title: "Verifarma", resizable: false, draggable: true, width:'1024px', buttons: [{text: oif_texto1, click: function() { print_iframe(link,$.browser.chrome); }}] }); $("#iFrame").dialog("option", "height", 720); print_iframe(link,$.browser.chrome); $("#iFrame").dialog('open'); } function print_iframe(link,boolean){ var pi_texto1 = "Due to policies in your browser, you cannot print several times. If you cannot print try opening the receipt from the list."; $("#iFrame").html(""); if(boolean){ $("#iFrame").html("

" + pi_texto1 + "

"); }else{ $("#iFrame").html(""); } } /* * Pop up para informacion de elemento desde el listado */ //inicia el div que tendra el dialog function iniciaPop(pop){ pop.dialog({ modal: false, autoOpen: false, title: "Verifarma", resizable: true, draggable: true, show: "clip" }); $(".link-listado").click(function(){ var ide = $(this).attr("ide"); var title_alt = $(this).attr("title_alt"); var title = $(this).attr("title"); if(ide=='' || ide==undefined){ ide = $(this).text(); } if(title=='' || title==undefined){ title = ''; } if(title_alt=='' || title_alt==undefined){ title_alt = $(this).text(); } title += ' ' + title_alt; pop.dialog("option", "title", title); pop.dialog("option", "height", $(this).attr("pheight")); pop.dialog("option", "width", $(this).attr("pwidth")); doWork($(this).attr("href"), 'id='+ide.replace(/\+/g,"%2B"), "poplistado"); pop.dialog('open'); return false; }); } //inicia el link-estado que se cargan por ajax function iniciaPopLink(pop){ $(".link-listado").click(function(){ var ide = $(this).attr("ide"); if(ide=='' || ide==undefined){ ide = $(this).text(); } pop.dialog("option", "title", $(this).attr("title")+' '+$(this).text()); pop.dialog("option", "height", $(this).attr("pheight")); pop.dialog("option", "width", $(this).attr("pwidth")); doWork($(this).attr("href"), 'id='+ide.replace(/\+/g,"%2B"), "poplistado"); pop.dialog('open'); return false; }); } // Autocomplete en inputs function crearAutocomplete(inp){ inp.each(function(){ $(this).autocomplete({ source: $(this).attr("url"), minLength: 2, select: function( event, ui ) { if($(this).attr("out")!=undefined && $(this).attr("out")!=''){ $($(this).attr("out")).val(ui.item.id); } if($(this).attr("callback")!=undefined && $(this).attr("callback")!=''){ eval($(this).attr("callback")); } } }); }); } // Autocomplete para lote_original function crearAutocompleteLoteOriginal(inp){ inp.each(function(){ $(this).autocomplete({ source: $(this).attr("url"), minLength: 2, select: function( event, ui ) { if($(this).attr("out")!=undefined && $(this).attr("out")!=''){ $($(this).attr("out")).val(ui.item.id); $($(this).attr("out")).attr("desactivado", ui.item.desactivado); } if($(this).attr("callback")!=undefined && $(this).attr("callback")!=''){ eval($(this).attr("callback")); } } }); }); } // autocomplete especial para lotes en comprobantes function crearAutocompleteLote(inp,from){ var completeFrom = ( from && from != '' ) ? "&from="+from : ""; inp.each(function(){ $(this).autocomplete({ minLength: 1, search: function(){ $(this).autocomplete( "option", "source", $(this).attr("url")+"?idm="+$(this).parent().parent().attr("idm")+completeFrom); }, open: function(){ $(this).attr("busca","1"); }, select: function( event, ui ) { if($(this).attr("out")!=undefined && $(this).attr("out")!=''){ $($(this).attr("out")).val(ui.item.id); if(ui.item.code != undefined){ $($(this).attr("out")).attr("code", ui.item.code); } } }, close: function( event, ui ) { $(this).attr("busca","0"); if($(this).attr("callback")!=undefined && $(this).attr("callback")!=''){ eval($(this).attr("callback")); } } }); }); } function crearAutocompleteLoteWithMed(inp,med){ inp.each(function(){ $(this).autocomplete({ minLength: 1, search: function(){ $(this).autocomplete( "option", "source", $(this).attr("url")+"?idm="+med); }, open: function(){ $(this).attr("busca","1"); }, select: function( event, ui ) { if($(this).attr("out")!=undefined && $(this).attr("out")!=''){ $($(this).attr("out")).val(ui.item.id); } }, close: function( event, ui ) { $(this).attr("busca","0"); if($(this).attr("callback")!=undefined && $(this).attr("callback")!=''){ eval($(this).attr("callback")); } } }); }); } function crearAutocompleteLoteWithMedIfExist(inp){ inp.each(function(){ $(this).autocomplete({ minLength: 1, search: function(){ $(this).autocomplete( "option", "source", $(this).attr("url")+"?idm="+$('#cmdIdMedicamento').val()); }, open: function(){ $(this).attr("busca","1"); }, select: function( event, ui ) { if($(this).attr("out")!=undefined && $(this).attr("out")!=''){ $($(this).attr("out")).val(ui.item.id); } }, close: function( event, ui ) { $(this).attr("busca","0"); if($(this).attr("callback")!=undefined && $(this).attr("callback")!=''){ eval($(this).attr("callback")); } } }); }); } // Borrar el id generado por el autocomplete function resetIdAutocomplete ( e ) { $( e ).keypress( function(){ $( this ).next().val( '' ) }); } // Funcion para limpiar codigos cuando se ingresan function sanitaze_codigo(str) { return str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''); } function trim(text){ return text.replace(/([\s]){1,}/g, ''); } /* Unas utilidades */ function console_log(mensaje){ //console.log(mensaje); } //******************* GS1-RFID ***************** /** * Recibe un string con el formato de la lectura del rfid, * lo descifra y devuelve el gtin + serie, que es ni mas ni menos * que el viejo y querido id_item */ var Rfid2IdItemConverter = new function() { var _errorValue = undefined; // Defino metodos /** * Saca todos los espacios de afuera y adentro de la cadena */ var trimAllSpaces = function(text) { return text.replace(/([\s]){1,}/g, ''); }; /** * Verifica si el valor es hexadecimal */ var isHexaValue = function(hexa_value) { return /^[0-9A-Fa-f]{1,}$/.test(hexa_value); }; /** * Llena el string con ceros al principio hasta cierto largo */ var zerosPad = function(str, len ){ str = "" + str; return str.length < len ? zerosPad("0"+ str, len) : str; }; /** * Devuelve el binario para el hexa que se le pasa como parametro */ var getBinaryStringFromHexa = function(hexa_value) { var binaryStringValue = ""; for ( var i in hexa_value ) { if( isHexaValue(hexa_value[i]) ) { binaryStringValue += zerosPad(parseInt(hexa_value[i],16).toString(2), 4); } } return binaryStringValue; }; /** * Devuelve un objeto con las partes del string */ var getBinarySections = function(binaryString) { var parts = { header: binaryString.substr(0, 8), filter: binaryString.substr(8, 3), // 3 partition: binaryString.substr(11, 3), // 3 company_prefix: binaryString.substr(14, 24), // 24 company: binaryString.substr(38, 20), // 20 serial: binaryString.substr(58, 38) // 38 }; return parts; } /** * Verifica si es valido el string segun sus partes */ var isValidBinaryStringBySections = function(binaryParts) { if( binaryParts.header != "00110000" ) { return false; } if( binaryParts.partition != "101" ) { return false; } return true; } /** * Devuelve los datos extraidos del binario pasados de formato * y completos si es necesario */ var getDataFromBinarySections = function(binarySections) { var data = { codigo_pais: zerosPad(parseInt(binarySections.company_prefix,2).toString(10), 7), codigo_empresa: zerosPad(parseInt(binarySections.company,2).toString(10), 6), serial: parseInt(binarySections.serial,2).toString(10) }; return data; } /** * Calcula el digito verificador para el gtin de 13 (ccc13) */ var getGtin13CheckDigit = function(text12) { var factor = 3; var sum = 0; for ( var i = text12.length; i > 0; --i ) { sum = sum + text12.substring (i-1, i) * factor; factor = 4 - factor; } var ccc13 = ((1000 - sum) % 10); return ccc13; }; /** * Devuelve el gtin para los datos pasados */ var getGtinFromData = function(data) { var codigos = data.codigo_empresa.toString().substr(0, 1) + data.codigo_pais.toString() + data.codigo_empresa.toString().substr(1) ; var gtin = codigos + getGtin13CheckDigit(codigos); return gtin; }; // Metodos publicos /** * Testea si es un valor SGtin-96 * */ this.isSgtin96 = function(value) { var clean_value = trimAllSpaces(value); if( clean_value.length != 24 || clean_value.substr(0,2) != "30" ) { // 30 = 00110000 return false; } return true; } /** * Devuelve el id_item convertido del valor del rfid */ this.getIdItem = function(rfid_value) { var clean_value = trimAllSpaces(rfid_value); if( clean_value.length != 24 ) { return _errorValue; } var binaryString = getBinaryStringFromHexa(clean_value); if( binaryString.length != ( 24 * 4 ) ) { return _errorValue; } var binarySections = getBinarySections(binaryString); // Verifica las secciones if( !isValidBinaryStringBySections(binarySections) ) { return _errorValue; } // Si esta bien, tomo los datos: var data = getDataFromBinarySections(binarySections); var gtin = getGtinFromData(data); var serial = data.serial; var id_item = "01" + gtin + "21" + serial; return id_item; }; /** * Testea si es un valor rfid sgtin96 y lo devuelve * Sino devuelve el mismo valor que se le paso * */ this.testAndGetIdItem = function(value) { if( !this.isSgtin96(value) ) { return value; } var id_item = this.getIdItem(value); if( id_item == _errorValue ) { return value; } return id_item; }; }; //******************* / GS1-RFID ***************** /* Ingreso manual prevent */ var m = 0; var _ingreso = { solo_scanner: false, solo_scanner_global: false, caracter_inicio_ok: false, largo: 0, fuePegado: false, caracteres_reservados: [36], letras_reservadas: ['$'], inputsForClear: ['codigo'], setSoloScanner: function() { this.solo_scanner = true; }, setSoloScannerGlobal: function(seteado) { this.solo_scanner_global = seteado; }, setFuePegado: function() { this.fuePegado = true; if(this.solo_scanner && !this.caracterInicioIsOk()){ window.setTimeout(this.addBombKey,4); } }, addBombKey: function(){ _ingreso.resetCodigoInIfNotEnableManualType(97); }, resetSoloScanner: function() { this.solo_scanner = false; }, caracterInicioIsOk: function() { return this.caracter_inicio_ok; }, resetIngreso: function() { this.caracter_inicio_ok = false; }, isCaracterReservado: function(tecla) { for( i in this.caracteres_reservados ) { if( this.caracteres_reservados[i] == tecla ) { return true; } } return false; }, isLetraReservada: function(letra) { for( i in this.letras_reservadas ) { if( this.letras_reservadas[i] == letra ) { return true; } } return false; }, setInputsForClear: function(inputs) { this.inputsForClear = inputs; }, clearCodigo: function() { codigo_in = ''; for( j in this.inputsForClear ) { $('#'+this.inputsForClear[j]).val(''); } this.largo = 0; }, resetCodigoInIfNotEnableManualType: function(tecla) { if(this.isCaracterReservado(tecla) && this.largo==0) { this.caracter_inicio_ok = true; this.clearCodigo(); return; } if(this.solo_scanner && tecla == 13 && this.fuePegado && !this.caracterInicioIsOk()){ this.clearCodigo(); this.fuePegado = false; return; } if(this.solo_scanner && !this.caracterInicioIsOk()) { this.clearCodigo(); return; } if(tecla == 13){ this.resetIngreso(); this.largo = 0; return; } this.largo++; }, resetCodigosIfNotLetraManualType: function() { if(this.solo_scanner_global){ var inputActual = $("input:focus"); if(inputActual.length==0){ inputActual = $("textarea:focus"); if(inputActual.length==0){ return false; } } var letra = inputActual.val(); for( j in this.inputsForClear ) { if(letra!='' && this.inputsForClear[j]==inputActual.attr("id") && this.solo_scanner && (!this.caracterInicioIsOk() || this.isLetraReservada(letra[0])) ) { $('#'+this.inputsForClear[j]).val(''); } } if(letra!='' && this.isLetraReservada(letra[0])){ inputActual.val(''); } } } }; //_ingreso.setSoloScanner(); /*** Zoom prevent ****/ var _g = { ctrlOn: false, ctrlKey: 17, plusKeys: [187, 107, 43, 171, 61, 93], gsKeys: [0, 18, 29, 93, 221, 186, 119], getTecla: function(e) { var tecla = null; e = e || window.event; if( e.keyCode ) tecla = e.keyCode; if( e.which ) tecla = e.which; return tecla; } }; document.onkeypress = function(e) { var tecla = _g.getTecla(e); if(_ingreso.solo_scanner_global){ // Sino esta habilitado el ingreso manual borra todo _ingreso.resetCodigoInIfNotEnableManualType(tecla); } }; document.onkeyup = function(e) { var tecla = _g.getTecla(e); DEBUG_SCANNER.debugMessage("onkeyup", tecla, codigo_in); if(_ingreso.solo_scanner_global){ _ingreso.resetCodigosIfNotLetraManualType(); } if( tecla == _g.ctrlKey ) { _g.ctrlOn = false; } }; // el evento onpaste se agrega de esta forma para compatibilidad con IE // los eventos de teclado se habilitan solo para cuando solo_scanner_global esta activado $(document).ready(function() { if(_ingreso.solo_scanner_global){ $('body').bind('paste', function() { _ingreso.setFuePegado(); _ingreso.resetCodigosIfNotLetraManualType(); }); $('body input').bind('blur', function() { _ingreso.largo = 0; }); } }); document.onkeydown = function(e) { var tecla = _g.getTecla(e); DEBUG_SCANNER.debugMessage("onkeydown", tecla, codigo_in); if( tecla == _g.ctrlKey ) { DEBUG_SCANNER.debugMessage("CTRL Detected", tecla, codigo_in); _g.ctrlOn = true; } if( _g.ctrlOn ) { for( i in _g.plusKeys ) { if( _g.plusKeys[i] == tecla ) { DEBUG_SCANNER.debugMessage("GS Detected (CTRL)", tecla, codigo_in); codigo_in += ''; return false; } } } for( i in _g.gsKeys ) { if( _g.gsKeys[i] == tecla ) { DEBUG_SCANNER.debugMessage("GS Detected", tecla, codigo_in); codigo_in += ''; return false; } } }; /*** End Zoom prevent ****/ // lectura de DataMatrix var codigo_in = ''; var pegado = false; var DEBUG_SCANNER = { isDebug: false, setActive : function(){ this.isDebug = true; }, debugMessageImpl: function(method, charCode, codigo_in) { console.log("[" + method +"] T:" + charCode + " C: " + String.fromCharCode(charCode) + " CI: " + codigo_in); }, debugMessage: function(method, charCode, codigo_in) { if (this.isDebug) { this.debugMessageImpl(method, charCode, codigo_in); } } }; function ingresoCodigo(valor, e){ //var tecla = (document.all) ? e.keyCode : e.which; var tecla = _g.getTecla(e); DEBUG_SCANNER.debugMessage("ingresoCodigo", tecla, codigo_in); if( _g.ctrlOn ) { DEBUG_SCANNER.debugMessage("CTRL IS ON", tecla, codigo_in); return; } if(tecla == 93 || tecla == 221 || tecla == 29){ if(codigo_in==''){ DEBUG_SCANNER.debugMessage("GS Detected (ingreso codigo tecla)", tecla, codigo_in); codigo_in += ''+String.fromCharCode(tecla); }else{ DEBUG_SCANNER.debugMessage("GS Detected (ingreso codigo)", tecla, codigo_in); codigo_in += ''; } }else { codigo_in += String.fromCharCode(tecla); } } // Para ingreso de codigos con handheld y pegados con ctrl+v function ingresoPegado(valor, e){ pegado = true; } // parseo de datamatrix function parsear_datamatrix(dm, tipo){ var nhrn_size = 13; var serial_preffix = '21'; var licitacion_preffix = '90'; var lote_preffix = '10'; var vto_preffix = '17'; var vto_size = 8; var gln_preffix = '414'; var gln_preffix_size = 3; var gln_size = 13; var dosis_preffix = 250; var dosis_preffix_size = 3; var gtin_preffix = '01'; var gtin_preffix_size = 2; var gtin_size = 14; var use_nhrn = false; var key_length = 4; var signature_length = 88; var pd_texto1 = "The datamatrix value is not valid."; var pd_texto2 = "Error code not set"; var pd_texto3 = "The Serial Number prefix is not valid %1."; var pd_texto4 = "The Serial Number must have a GTIN/NTIN, GLN or NHRN."; var pd_texto5 = "The Serial Number cannot have a series %1 longer than 20 digits."; var pd_texto6 = "The Data Matrix cannot have a GTIN/NTIN/GLN %1 longer than 13 digits."; var pd_texto7 = "The Serial Number with GLN cannot have a serial longer than 7."; if(dm == ''){ return new Array('','','','','',false, pd_texto1,''); } if(pegado){ codigo_in = dm.replace(/\x1D/g,''); } else if( codigo_in.replace('', '') != dm ) { //confirm( 'codigo_in: ' + codigo_in + '
' + 'dm: ' + dm ); if( !(new RegExp('\')).test(codigo_in) ) { codigo_in = dm; } } if( tipo == undefined || tipo == '' || tipo.toUpperCase() == 'RFID' ) { var cod = Rfid2IdItemConverter.testAndGetIdItem(codigo_in); }else{ var cod = codigo_in; } cod = sanitaze_codigo(cod); //cod = cod.toUpperCase(); if(tipo=='item' || tipo=='dosis' || tipo==undefined || tipo==''){ var gtin = ''; var serial = ''; var lote = ''; var vto = ''; var dosis = ''; var licitacion = ''; var nhrn = ''; var key = ''; var signature = ''; var keysignature = ''; var datos = cod.split(''); var preffix = ''; var invalidPreffix = false; for (var i = 0; i < datos.length; i++) { while (datos[i].length > 0) { if (datos[i].substr(0,3) == ']D2' || datos[i].substr(0,3) == ']d2') { datos[i] = datos[i].substr(3, datos[i].length); } else if (datos[i].substr(0,gtin_preffix_size) == gtin_preffix) { preffix = (preffix != '') ? preffix : datos[i].substr(0, 2); gtin = datos[i].substr(2,gtin_size); datos[i] = datos[i].substr(gtin_preffix_size+gtin_size, datos[i].length); } else if (datos[i].substr(0,gln_preffix_size) == gln_preffix) { preffix = (preffix != '') ? preffix : gln_preffix; gtin = datos[i].substr(gln_preffix_size,gln_size); datos[i] = datos[i].substr(gln_preffix_size+gln_size, datos[i].length); } else if (datos[i].substr(0,2) == lote_preffix) { lote = datos[i].substr(2,datos[i].length); datos[i] = ''; } else if (datos[i].substr(0,2) == vto_preffix) { vto = (datos[i].substr(6,2)=="00"?"":datos[i].substr(6,2)+"/")+datos[i].substr(4,2)+"/20"+datos[i].substr(2,2); datos[i] = datos[i].substr(vto_size, datos[i].length); } else if (datos[i].substr(0,2) == '11') { datos[i] = datos[i].substr(vto_size, datos[i].length); } else if (datos[i].substr(0,2) == serial_preffix) { serial = datos[i].substr(2,datos[i].length); datos[i] = ''; } else if (datos[i].substr(0,dosis_preffix_size) == dosis_preffix) { dosis = datos[i].substr(dosis_preffix_size,datos[i].length); datos[i] = ''; } else if (datos[i].substr(0,2) == licitacion_preffix) { licitacion = datos[i].substr(2, datos[i].length); datos[i] = ''; } else if (datos[i].substr(0,3) == '710' || datos[i].substr(0,3) == '711' || datos[i].substr(0,3) == '713') { if (use_nhrn) { preffix = datos[i].substr(0,3); } if (nhrn_size != 0) { nhrn = datos[i].substr(3,nhrn_size); datos[i] = datos[i].substr(3+nhrn_size, datos[i].length); } else { nhrn = datos[i].substr(3,datos[i].length); datos[i] = ''; } } else if (datos[i].substr(0,2) == '91') { key = datos[i].substr(2,key_length); keysignature = datos[i].substr(0,key_length+2); datos[i] = datos[i].substr(key_length+2, datos[i].length); } else if (datos[i].substr(0,2) == '92') { signature = datos[i].substr(2,signature_length); keysignature = keysignature + datos[i].substr(0,signature_length+2); datos[i] = datos[i].substr(signature_length+2, datos[i].length); } else if (datos[i].substr(0,3) == '712' || datos[i].substr(0,3) == '714') { /* Actualmente la BD no posee los campos para estos codigos y por ende no se deben almacenar, a la espera para su agregacion */ datos[i] = ''; } else { invalidPreffix = datos[i]; datos[i] = ''; break; } } } var codigoArr = new Array('','','','','',false, pd_texto2,''); if(invalidPreffix != false){ codigoArr = new Array('','','','','',false, pd_texto3.format([invalidPreffix]),''); } else if( (gtin=='' || nhrn=='') && serial==''){ codigoArr = new Array('','','','','',false, pd_texto4,''); } else if (serial.length>20){ codigoArr = new Array('','','','','',false, pd_texto5.format([serial]),''); } else if(gtin.length>gtin_size){ codigoArr = new Array('','','','','',false, pd_texto6.format([gtin]),''); } else if (preffix == '414' && serial.length>7) { codigoArr = new Array('','','','','',false, pd_texto7,''); /* } else if (preffix == '414' && (lote != '' || vto != '')) { codigoArr = new Array('','','','','',false, 'La etiqueta con GLN no puede contener lote o vencimiento.',''); */ } else { var code = (nhrn != '' && use_nhrn) ? nhrn : gtin; codigoArr = new Array(gtin,serial,lote,vto,(preffix + code + serial_preffix + serial), true, 'OK',dosis,licitacion,nhrn,key,signature,keysignature); } }else{ codigoArr = new Array('','','','',cod, true, 'OK',''); } if (codigoArr[5] === false) { $.ajax({ type: "POST", url: '/modulos/general/audit_trail', cache: false, data: "new="+cod+"&old="+codigo_in }); } codigo_in = ''; pegado = false; return codigoArr; } // parseo de datamatrix function parsear_datamatrix_sedronar(dm, tipo){ if(dm == ''){ return new Array('','','','','',false, 'El valor del datamatrix es invalido.',''); } if(pegado){ codigo_in = dm.replace(/\x1D/g,''); } else if( codigo_in.replace('', '') != dm ) { //confirm( 'codigo_in: ' + codigo_in + '
' + 'dm: ' + dm ); if( !(new RegExp('\')).test(codigo_in) ) { codigo_in = dm; } } if( tipo == undefined || tipo == '' || tipo.toUpperCase() == 'RFID' ) { var cod = Rfid2IdItemConverter.testAndGetIdItem(codigo_in); }else{ var cod = codigo_in; } cod = sanitaze_codigo(cod); //cod = cod.toUpperCase(); if(tipo=='item' || tipo=='dosis' || tipo==undefined || tipo==''){ var gtin = ''; var serial = ''; var lote = ''; var vto = ''; var dosis = ''; var licitacion = ''; var datos = cod.split(''); var preffix = ''; var invalidPreffix = false; for (var i = 0; i < datos.length; i++) { while (datos[i].length > 0) { if (datos[i].substr(0,3) == ']D2' || datos[i].substr(0,3) == ']d2') { datos[i] = datos[i].substr(3, datos[i].length); } else if (datos[i].substr(0,2) == '01') { preffix = '01'; gtin = datos[i].substr(2,14); datos[i] = datos[i].substr(16, datos[i].length); } else if (datos[i].substr(0,3) == '414') { preffix = '414'; gtin = datos[i].substr(3,13); datos[i] = datos[i].substr(16, datos[i].length); } else if (datos[i].substr(0,2) == '10') { lote = datos[i].substr(2,datos[i].length); datos[i] = ''; } else if (datos[i].substr(0,2) == '17') { vto = (datos[i].substr(6,2)=="00"?"":datos[i].substr(6,2)+"/")+datos[i].substr(4,2)+"/20"+datos[i].substr(2,2); datos[i] = datos[i].substr(8, datos[i].length); } else if (datos[i].substr(0,2) == '11') { datos[i] = datos[i].substr(8, datos[i].length); } else if (datos[i].substr(0,2) == '21') { serial = datos[i].substr(2,datos[i].length); datos[i] = ''; //serial = datos[i].substr(2,10); //datos[i] = datos[i].substr(12, datos[i].length); } else if (datos[i].substr(0,3) == '250') { dosis = datos[i].substr(3,datos[i].length); datos[i] = ''; } else if (datos[i].substr(0,2) == '90') { licitacion = datos[i].substr(2,datos[i].length); datos[i] = ''; } else { invalidPreffix = datos[i]; datos[i] = ''; break; } } } var codigoArr = new Array('','','','','',false, 'Codigo de error no seteado',''); if(invalidPreffix != false){ codigoArr = new Array('','','','','',false, 'El prefijo de la etiqueta es invalido ' + invalidPreffix + '.',''); } else if(gtin==''){ codigoArr = new Array('','','','','',false, 'La etiqueta debe contener un GTIN/NTIN y/o GLN.',''); } else if (serial.length>20){ codigoArr = new Array('','','','','',false, 'La etiqueta no puede contener un serie ' + serial + ' mayor a 20 digitos.',''); } else if(gtin.length>14){ codigoArr = new Array('','','','','',false, 'La etiqueta no puede contener un GTIN/NTIN/GLN ' + gtin + ' mayor a 14 digitos.',''); } else if (preffix == '414' && serial.length>7) { codigoArr = new Array('','','','','',false, 'La etiqueta con GLN no puede tener un serial mayor a 7.',''); /* } else if (preffix == '414' && (lote != '' || vto != '')) { codigoArr = new Array('','','','','',false, 'La etiqueta con GLN no puede contener lote o vencimiento.',''); */ } else { codigoArr = new Array(gtin,serial,lote,vto,(serial!=''?(preffix+gtin+'21'+serial):gtin), true, 'OK',dosis,licitacion); } }else{ codigoArr = new Array('','','','',cod, true, 'OK',''); } codigo_in = ''; pegado = false; return codigoArr; } var codes_prefix = false; function getCodesPrefix(){ if(codes_prefix !== false){ return true; } var get_codes_prefix_url = "https://photocure-testing.verifarma.com/modulos/etiquetas/get_codes_prefix"; var exito = false; $.ajax({ type: "GET", url: get_codes_prefix_url, dataType: "json", cache: false, async: false, success: function( data, textStatus, jqXHR ) { codes_prefix = data; exito = true; }, fail: function( jqXHR, textStatus, errorThrown ) { console.log( "Fallo: " + textStatus); } }); return exito; } function getCodeTypeFromDatabase(code){ let code_type = ''; if(!getCodesPrefix()){ return ''; } let key_type = code.substr(0,2); let filter_value = code.substr(2,1); let suffix = code.substr(3); let cp_suffix = code.substr(0,3); let ean = code.substr(3,13); let cp = code.substr(3,7); if( key_type == '' || filter_value == '' || codes_prefix[key_type] === undefined || codes_prefix[key_type] === null || codes_prefix[key_type] === '' || codes_prefix[key_type][filter_value] === undefined || codes_prefix[key_type][filter_value] === null || codes_prefix[key_type][filter_value] === '' ){ return ''; } var posible_types = codes_prefix[key_type][filter_value][ean]; if(posible_types == undefined){ posible_types = codes_prefix[key_type][filter_value][cp]; } if(posible_types == undefined){ return ''; } Object.keys(posible_types).forEach(function(prefix){ if(suffix.startsWith(prefix)){ code_type = posible_types[prefix]; } if(cp_suffix.startsWith(prefix)){ code_type = posible_types[prefix]; } }); switch(code_type){ case 'E': {code_type = "item"; break;} case 'P': {code_type = "pack"; break;} case 'L': {code_type = "pallet"; break;} case 'C': {code_type = "box"; break;} default: {code_type = ''; break;} } return code_type; } function getCodigoTipo(codigoLeido){ if(codigoLeido==''){ return ''; } var tipo = ''; if(Rfid2IdItemConverter.isSgtin96(codigoLeido)){ tipo = 'RFID'; }else{ tipo = getCodeTypeFromDatabase(codigoLeido); if(tipo !== '') return tipo; var identificador = codigoLeido.substr(0,3); switch(identificador){ case '010': case '018': case '888': case '414': case '710': case '711': case '712': case '713': {tipo = "item"; break;} case '000': {tipo = "pack"; break;} case '002': {tipo = "pack"; break;} case '001': {tipo = "pallet"; break;} case '003': {tipo = "pallet"; break;} case '007': {tipo = "pallet"; break;} } if(tipo==''){ identificador = codigoLeido.substr(0,2); switch(identificador){ case '01': {tipo = "item"; break;} case '88': {tipo = "item"; break;} case '10': {tipo = getCodigoTipo(codigoLeido.substr(16)); break;} } } } return tipo; } // redirige al dashboard, funcion para cancelar function irInicio(){ document.location.href="/modulos/general/main"; } // Para Internet Explorer. Redefinicion de IndexOf if(!Array.indexOf){ Array.prototype.indexOf = function(obj, start) { for (var i = (start || 0), j = this.length; i < j; i++) { if (this[i] === obj) { return i; } } return -1; } } if (!String.prototype.startsWith) { Object.defineProperty(String.prototype, 'startsWith', { value: function(search, pos) { pos = !pos || pos < 0 ? 0 : +pos; return this.substring(pos, pos + search.length) === search; } }); } // Rellena con ceros el valor pasado function rellenar_ceros(obj,ceros){ var valor = $(obj).val(); if(valor!='' && valor.length0){ if(parseInt(mt[0])<0 || parseInt(mt[0])>23 || parseInt(mt[1])<0 || parseInt(mt[1])>59){ mytime = hora_actual; } }else{ mytime = hora_actual; } $(ii).val(mytime); } //valida que un email tenga un formato valido function validaEmail(valor){ // creamos nuestra regla con expresiones regulares. var filter = /[\w-\.]{3,}@([\w-]{2,}\.)*([\w-]{2,}\.)[\w-]{2,4}/; // utilizamos test para comprobar si el parametro valor cumple la regla if(filter.test(valor)) return true; else return false; } // para fechas de vencimiento con dia = 00. Saca los ceros function zero_days(date){ if(date!='' && date!=undefined){ if(date.substr(0,3)=='00/'){ date = date.substr(3); } } return date; } // suma una cantidad de dias a la fecha pasada (dd/mm/yyyy) function addDays(date,days){ if(date!=undefined && days!=undefined){ var sumDays = parseInt(days); var parseDate = date.split("/"); if(parseDate.length < 3){ return date; }else{ var newDate = new Date(parseDate[2].toString() +'/'+ parseDate[1].toString() +'/'+ parseDate[0].toString()); newDate.setDate(newDate.getDate()+sumDays); var year=newDate.getFullYear(); var month= newDate.getMonth()+1; var day= newDate.getDate(); if(month.toString().length<2){ month="0".concat(month); } if(day.toString().length<2){ day="0".concat(day); } return day+'/'+month+'/'+year; } }else{ return date; } } // inicializa los iconos para exportar a PDF function iniciar_export(url,nombre_form,variables){ $(".exportar").unbind('click'); $(".exportar").click(function(){ if(nombre_form==""){ nombre_form = "export"; var form_export = '
'; $('body').append(form_export); }else{ $("#"+nombre_form).attr("action",url); } var inputs = ""; var tipo = $(this).attr("tipo"); var tipoval = $("#"+tipo).val(); if(tipoval==undefined){ inputs = ''; } var miv = ""; var valor = ""; for (var i = 0; i < variables.length; i++){ miv = variables[i]; valor = $("#"+miv).val(); if(valor!=undefined){ eval("var "+miv+" = '"+$("#"+miv).val()+"'"); inputs += ''; } } $('#'+nombre_form).append(inputs); $("#"+nombre_form).submit(); if(nombre_form == "export"){ $("#"+nombre_form).remove(); } $("#"+tipo).remove(); return false; }); } function iniciar_export3(url,nombre_form,variables){ $(".exportar3").unbind('click'); $(".exportar3").click(function(){ if(nombre_form==""){ nombre_form = "export"; var form_export = '
'; $('body').append(form_export); }else{ $("#"+nombre_form).attr("action",url); } var inputs = ""; var tipo = $(this).attr("tipo"); var tipoval = $("#"+tipo).val(); if(tipoval==undefined){ inputs = ''; } var miv = ""; var valor = ""; for (var i = 0; i < variables.length; i++){ miv = variables[i]; valor = $("#"+miv).val(); if(valor!=undefined){ eval("var "+miv+" = '"+$("#"+miv).val()+"'"); inputs += ''; } } $('#'+nombre_form).append(inputs); $("#"+nombre_form).submit(); if(nombre_form == "export"){ $("#"+nombre_form).remove(); } $("#"+tipo).remove(); return false; }); } function iniciar_export2(url,nombre_form,variables){ $(".exportar2").unbind('click'); $(".exportar2").click(function(){ if(nombre_form==""){ nombre_form = "export"; var form_export = '
'; $('body').append(form_export); }else{ $("#"+nombre_form).attr("action",url); } var inputs = ""; var tipo = $(this).attr("tipo"); var tipoval = $("#"+tipo).val(); if(tipoval==undefined){ inputs = ''; } var miv = ""; var valor = ""; for (var i = 0; i < variables.length; i++){ miv = variables[i]; valor = $("#"+miv).val(); if(valor!=undefined){ eval("var "+miv+" = '"+$("#"+miv).val()+"'"); inputs += ''; } } $('#'+nombre_form).append(inputs); $("#"+nombre_form).submit(); if(nombre_form == "export"){ $("#"+nombre_form).remove(); } $("#"+tipo).remove(); return false; }); } function iniciar_export4(url,nombre_form,variables){ $(".exportar4").unbind('click'); $(".exportar4").click(function(){ if(nombre_form==""){ nombre_form = "export"; var form_export = '
'; $('body').append(form_export); }else{ $("#"+nombre_form).attr("action",url); } var inputs = ""; var tipo = $(this).attr("tipo"); var tipoval = $("#"+tipo).val(); if(tipoval==undefined){ inputs = ''; } var miv = ""; var valor = ""; for (var i = 0; i < variables.length; i++){ miv = variables[i]; valor = $("#"+miv).val(); if(valor!=undefined){ eval("var "+miv+" = '"+$("#"+miv).val()+"'"); inputs += ''; } } $('#'+nombre_form).append(inputs); $("#"+nombre_form).submit(); if(nombre_form == "export"){ $("#"+nombre_form).remove(); } $("#"+tipo).remove(); return false; }); } //inicializa los iconos para exportar a xls function iniciar_export_xls(){ var form_xls = '
'; $('body').append(form_xls); $('.xls_export').click(function(){ var datos = $('
').append($("#"+$(this).attr("rel")).clone()).remove().html(); $("#datos_xls").val(datos); $("#exportxls").submit(); return false; }); } function isValidRfid(codigo) { return (FULL_RFID_ENABLED || RFID_ENABLED) && codigo.length == 29 && codigo.substr(0, 4) == "E200"; } var pleaseWaitDialog; function showWaitDialog(text) { pleaseWaitDialog = $("#waitDialog").dialog( { resizable: false, height: 70, width: 280, modal: true, closeText: '', bgiframe: true, closeOnEscape: false, open: function(type, data) { $(this).parent().appendTo($("form:first")); $('body').css('overflow', 'auto'); //IE scrollbar fix for long checklist templates $(".ui-dialog-titlebar").hide(); $("#waitDialogMessage").html(text); }, close: function(type, data) { $(".ui-dialog-titlebar").show(); } }); $("#waitDialog").css("height","auto"); } function showWaitDialogEdi(text) { pleaseWaitDialog = $("#waitDialog").dialog( { resizable: false, height: 70, width: 280, modal: true, closeText: '', bgiframe: true, closeOnEscape: false, open: function(type, data) { $(this).parent().appendTo($("form:first")); $('body').css('overflow', 'auto'); //IE scrollbar fix for long checklist templates $(".ui-dialog-titlebar").hide(); $("#waitDialogMessage").html(text); }, close: function(type, data) { $(".ui-dialog-titlebar").show(); } }); $("#ajax-gif").attr("src","/img/edi.gif"); $("#ajax-gif").attr("width","30"); $("#ajax-gif").attr("height","30"); $("#waitDialog").css("height","30px"); $(".ui-dialog").css("width","350px"); var left = $(".ui-dialog").css("left"); var len = left.length; left = parseInt(left.substring(0, len - 2)); $(".ui-dialog").css("left", (left - (left * 0.1)) + "px"); $("#waitDialogMessage").css("padding-top","5px"); } function closeWaitDialog() { pleaseWaitDialog.dialog("close"); } // para el paginado de paginas function iniciarPaginado(url_post,tabla,offset,ajaxtype,variables){ var ip_texto1 = "Loading data..."; $(".pag-num").addClass(tabla); $("."+tabla).removeClass("pag-num"); $("."+tabla).click(function(){ var page = $(this).attr("page"); var totalCant = $("#totalCant_"+tabla).val(); var variables_ajax = ""; var miv = ""; var valor = ""; for (var i = 0; i < variables.length; i++){ miv = variables[i]; valor = $("#"+miv).val(); if(valor!=undefined){ eval("var "+miv+" = '"+$("#"+miv).val()+"'"); variables_ajax += "&"+miv+"="+eval(miv); } } if(ajaxtype==undefined) ajaxtype = "ajaxlist"; showWaitDialog(ip_texto1); $.ajax({ type: "POST", url: url_post, data: ajaxtype+"=1&page="+page+"&totalCant="+totalCant+variables_ajax, cache: false, success: function(msg) { closeWaitDialog(); $("#contienetabla_"+tabla).parent().html(msg); if(ajaxtype=='ajaxlist'){ iniciarTablas(tabla,offset,0); iniciarPaginado(url_post,tabla,offset,ajaxtype,variables); iniciaPopLink($("#poplistado")); } } }); return false; }); } function iniciarPaginado2(url_post,tabla,offset,ajaxtype,variables){ var ip_texto1 = "Loading data..."; $(".pag-num").addClass(tabla); $("."+tabla).removeClass("pag-num"); $("."+tabla).click(function(){ var page = $(this).attr("page"); var totalCant = $("#totalCant_"+tabla).val(); var variables_ajax = ""; var miv = ""; var valor = ""; for (var i = 0; i < variables.length; i++){ miv = variables[i]; valor = $("#"+miv).val(); if(valor!=undefined){ eval("var "+miv+" = '"+$("#"+miv).val()+"'"); variables_ajax += "&"+miv+"="+eval(miv); } } if(ajaxtype==undefined) ajaxtype = "ajaxlist"; showWaitDialog(ip_texto1); $.ajax({ type: "POST", url: url_post, data: ajaxtype+"=1&page="+page+"&totalCant="+totalCant+variables_ajax, cache: false, success: function(msg) { closeWaitDialog(); $("#contienetabla_" + tabla).html($(msg).find("#contienetabla_" + tabla).html()); if(ajaxtype=='ajaxlist'){ iniciarTablas(tabla,offset,0); iniciarPaginado2(url_post,tabla,offset,ajaxtype,variables); iniciaPopLink($("#poplistado")); } } }); return false; }); } function irPagina(ii,e){ var tecla = (document.all) ? e.keyCode : e.which; var pagina = $(ii).val(); if (tecla == 13 && pagina!='') { $(ii).next().attr("page",pagina); $(ii).next().click(); if(!e) var e = window.event; e.cancelBubble = true; e.returnValue = false; if(e.stopPropagation()){ e.stopPropagation(); e.preventDefault(); } return false; } } function limpiarLote(lote) { return lote.replace(/[+.#*%:;,<>@_\/\s]/g,'-'); } /* Para el logo de certisur */ function showSeal(host_name,lang,transparent,folder,filename,swfwidth,swfheight,loadURL){ if (transparent == "yes"){ var trans = "transparent"; } else { var trans = "window"; } /* document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); document.write('\n'); */ } function Seal_Certificado(host_name,lang,version,domain){ } /* * comprobamos el usuario y contraseƱa del usuario por ajax */ function checkLogin(callback,eventoLog){ aviso("BL","Verifarma",'Por favor complete sus datos de usuario:

Usuario:


Contraseña:

','',loginAjax,'0'); } function loginAjax(){ var la_texto1 = "Your user name or password is incorrect."; var username = $("#txtuser").val(); var pass = $("#txtpassword").val(); var callbck = $("#autcallback").val(); var evento_log = $("#autevento").val(); if(username!='' && pass!=''){ $.ajax({ type: "POST", url: '/modulos/general/loginAjax', cache: false, data: "txtuser="+username+"&txtpassword="+pass+"&eventolog="+evento_log, success: function(msg) { if(msg=='OK'){ eval(callbck); } else { aviso("AL","Verifarma",la_texto1); } } }); }else{ aviso("AL","Verifarma",la_texto1); } } /* * FIN - comprobamos el usuario y contraseƱa del usuario por ajax */ /* ----------------------------------------------------------------------------- Plugin: jquery.selectfixedwith.js Author: Albert Lanchas (http://www.albertlanchas.com) Demo: http://www.albertlanchas.com/en/utilidades/select-con-ancho-fijo-para-internet-explorer Version: 0.2 Description: Tries to solve the problem of select boxes with a fixed width on Internet Explorer. ----------------------------------------------------------------------------- */ (function($) { $.fn.selectfixedwidth = function(options) { var defaults = { // A timeout is needed to execute the change event handler before the // mousedown one and let IE hide the options list. 300ms works for me but // you might need to adjust this value. If it's too short a change event // handler won't be executed. Another behaviour affected by the timeout is // when the select box with its list deployed is double clicked. If it's // too short it will be expanded without the list being displayed and it // won't behave as expected timeout: 300 }; // Extend default options with those provided. var opts = $.extend(defaults, options); return $(this).each( function(i) { var $this = $(this); if (!jQuery.support.cssFloat && $this.is("select")) { // only if ie and a select box if (jQuery.browser.msie && jQuery.browser.version > 6) { // ie6 not supported // wrap the select and apply some css to avoid breaking up the layout when // expanding the select box var $span = $(''); $span.css({ display: "inline-block", width: parseInt($this.css("width")) + 4 + "px", height: $this.height() + "px" }); $this.css("position", "absolute"); $this.wrap($span); // original size read from the css $this.data("width", $(this).css("width")); // keeps state of the size $this.data("state", 'short'); // timeout var t; $this .mousedown( function() { if ($this.data("state") == 'short') { resize($this, 'long'); } else { t = setTimeout(function() { resize($this, 'short'); t = null; }, opts.timeout); } } ) .bind("blur change", function() { resize($this, 'short'); clearTimeout(t); t = null; } ) .dblclick( function() { if (t) { // if timeout is not null it means the select box has been double // clicked when the list was displayed. It doesnt need to be // shortened so the timeout is cleared and the variable reseted. clearTimeout(t); t = null; } else { resize($this, 'short'); } } ); } } } ); }; // private functions function resize($obj, state) { if (state == 'short') { $obj.css("width", $obj.data("width")); } else { $obj.css("width", "auto"); } $obj.data("state", state); }; })(jQuery); // Plug in para crear un Carousel (function($){ $.fn.infiniteCarousel = function (options) { //Set the default values, use comma to separate the settings var defaults = { clickFunction: '' } var options = $.extend(defaults, options); var showPage = 1; var focusElement = ''; var valid = true; // support multiple elements if (this.length > 1){ this.each(function() { $(this).infiniteCarousel(options); }); return this; } function repeat(str, num) { return new Array( num + 1 ).join( str ); } this.getPage = function() { return showPage; }; this.setFocus = function(el) { focusElement = el; }; this.setValid = function(tof){ valid = tof; } this.pageNotValid = function(invalid,current,state){ if(invalid == current && !state){ valid = false; }else{ valid = true; } return valid; } // public methods this.initialize = function() { var $wrapper = $('> div', this).css('overflow', 'hidden'), $slider = $wrapper.find('> ul'), $items = $slider.find('> li'), $single = $items.filter(':first'), singleWidth = $single.outerWidth(), visible = Math.floor($wrapper.innerWidth() / singleWidth), // note: doesn't include padding or border currentPage = 1, pages = Math.ceil($items.length / visible); // 1. Pad so that 'visible' number will always be seen, otherwise create empty items if (($items.length % visible) != 0) { $slider.append(repeat('
  • ', visible - ($items.length % visible))); $items = $slider.find('> li'); } // 2. Top and tail the list with 'visible' number of items, top has the last section, and tail has the first //$items.filter(':first').before($items.slice(- visible).clone().addClass('cloned')); //$items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned')); $items = $slider.find('> li'); // reselect // 3. Set the left position to the first 'real' item //$wrapper.scrollLeft(singleWidth * (visible)); $wrapper.scrollLeft(0); // 4. paging function function gotoPage(page) { var dir = page < currentPage ? -1 : 1, n = Math.abs(currentPage - page), left = singleWidth * dir * visible * n; $wrapper.filter(':not(:animated)').animate({ scrollLeft : '+=' + left }, 500, function () { if (page == 0) { $wrapper.scrollLeft(singleWidth * visible * pages); page = pages; } else if (page > pages) { $wrapper.scrollLeft(singleWidth * visible); // reset back to start position page = 1; } currentPage = page; showPage = currentPage; if(focusElement!=''){ $('#'+focusElement).focus(); focusElement = ''; } }); return false; } if(options.clickFunction != ""){ $wrapper.after('<>'); }else{ $wrapper.after('<>'); } // 5. Bind to the forward and back buttons $('a.back', this).click(function () { if((currentPage + 1) == pages || (currentPage - 1) == pages){ $(".back").show(); $(".forward").hide(); } if((currentPage + 1) == 1 || (currentPage - 1) == 1){ $(".back").hide(); $(".forward").show(); }else{ $(".back").show(); $(".forward").show(); } if(currentPage > 1){ return gotoPage(currentPage - 1); }else{ return currentPage; } }); $('a.forward', this).click(function () { if(!valid){ valid = true; return false; } if((currentPage + 1) == 1 || (currentPage - 1) == 1){ $(".back").hide(); $(".forward").show(); } if((currentPage + 1) == pages || (currentPage - 1) == pages){ $(".back").show(); $(".forward").hide(); }else{ $(".back").show(); $(".forward").show(); } if(currentPage < pages){ return gotoPage(currentPage + 1); } return currentPage; }); // create a public interface to move to a specific page $(this).bind('goto', function (event, page) { gotoPage(page); }); return this; }; return this.initialize(); } })(jQuery); function iniciar_export_xml(url, verificar, data, nombreinput){ var form_xls = '
    '; $('body').append(form_xls); $("#exportxml").submit(); $("#exportxml").remove(); } String.prototype.format = function (args) { var str = this; return str.replace(String.prototype.format.regex, function(item) { var intVal = parseInt(item.substring(1, item.length)); var replace; if (intVal >= 1) { replace = args[intVal-1]; } else if (intVal === -1) { replace = "%"; } else if (intVal === -2) { replace = " "; } else { replace = ""; } return replace; }); }; String.prototype.format.regex = new RegExp("%-?[0-9]+", "g"); function removeElementFromArray(arr, element){ arr = jQuery.grep(arr, function(value) { return value != element; }); return arr; } function generateHttpParameters(parameters) { var parametersString = ""; for (var i = 0; i < parameters.length; i++) { if (i !== 0) parametersString += "&"; parametersString += parameters[i].key + "=" + parameters[i].value; } return parametersString; } function refreshPage() { location.reload(true); } function IsValidJSONString( str ) { try { JSON.parse(str); } catch (e) { return false; } return true; } function onlyNumber( evt ) { var theEvent = evt || window.event; // Handle paste if ( theEvent.type === 'paste' ) { key = event.clipboardData.getData( 'text/plain' ); } else { // Handle key press var key = theEvent.keyCode || theEvent.which; key = String.fromCharCode( key ); } var regex = /[0-9]|\./; if( !regex.test(key) ) { theEvent.returnValue = false; if( theEvent.preventDefault ) theEvent.preventDefault(); } } function isNumberValue( value ) { var isNumber = /^\d+$/.test( value ); return isNumber; } //Limpia el val en todos los imput de la clase pasada function limpiarCampos(clase){ $("."+clase).each(function(){ $(this).val(''); }); } function generateEmvoFakeResponse(ee){ var url = $(ee).attr("url"); var idTrans = $(ee).attr("id"); var force_error = $(ee).attr("force_error"); if(force_error == undefined || force_error == ""){ force_error = "0"; } if(idTrans!='' && url != ""){ $.ajax({ type: "POST", url: url, cache: false, data: "idTrans="+idTrans+"&force_error="+force_error, success: function(msg) { if(msg!='OK'){ aviso("ER","Verifarma",msg,"",refreshPage); }else{ aviso("OK","Verifarma",msg,"",refreshPage); } } }); } } function checkEmvoStatus(item, gtin, cod_lote, fecha_vto, success, error){ var urlProductos = "https://photocure-testing.verifarma.com/modulos/productos/"; if(item == "" || cod_lote == "" || fecha_vto == ""){ error(item, "DATA"); } if(!gtin){ var data = parsear_datamatrix(item, "item"); gtin = data[0]; } var req = { "id": item, "conestadoemvo": 1, "gtin" : gtin, "cod_lote" : cod_lote, "fecha_vto" : fecha_vto, }; var formData = createDataForm(req); $.ajax({ type: "POST", url: urlProductos + "get_estado_emvo_item_do", data: formData, processData: false, contentType: false, cache: false, success: function(msg) { msg = msg.split("_"); var r = { 'state': msg[0], 'serial': msg[1], 'emvoState': msg[2], 'error': msg[3]? msg[3] : text_error_general_js }; success(item, r); }, error: function() { error(item, "ERROR-500"); }, complete: function(){ //... }, timeout: 10000 // sets timeout to 10 seconds }); } function acomodar_colores(){ $("#lista_items tr").removeClass("odd even"); $("#lista_items tr:odd").addClass("odd"); $("#lista_items tr:even").addClass("even"); $(".lista_items tr").removeClass("odd even"); $(".lista_items tr:odd").addClass("odd"); $(".lista_items tr:even").addClass("even"); } function contar(contador, valor){ var nuevo = parseInt($("#"+contador).html()) + parseInt(valor); $("#"+contador).html(nuevo); } function fechaSinDia(e, elem){ var checkValue = $(e).prop( 'checked' ); var Sinput = $( elem ); var dateInput = Sinput.val(); var newValue; if ( checkValue ){ if( dateInput != '' ) { newValue = dateInput.substr(3); Sinput.val( newValue ); } Sinput.datepicker( "destroy" ); Sinput.datepicker({ changeYear: true, changeMonth: true, showButtonPanel: true, dateFormat: 'mm/yy', minDate: 1, onClose: function() { var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val(); var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val(); $(this).datepicker('setDate', new Date(year, month, 1)); } }); Sinput.focus(function () { $("#ui-datepicker-div").css('transform','translateY(40px)'); $(".ui-datepicker-calendar").hide(); }); } else { Sinput.val( '' ); Sinput.datepicker( "destroy" ); Sinput.datepicker({ dateFormat: 'dd/mm/yy', changeYear: false, changeMonth: false, minDate: 1 }); Sinput.focus(function () { $("#ui-datepicker-div").css('transform','translateY(0px)'); $(".ui-datepicker-calendar").show(); }); } } function generateXLSX(fileName, headers, data) { const date = new Date(); if(fileName == '') { fileName = "Verifarma_" + date.getFullYear() + date.getMonth() + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds(); } fileName += '.xlsx'; const workbook = new ExcelJS.Workbook(); const worksheet = workbook.addWorksheet('Verifarma'); let titleRow = worksheet.addRow([]); titleRow.font = { name: 'Calibri', bold: true }; worksheet.columns = headers; worksheet.addRows(data); const PIXELS_PER_EXCEL_WIDTH_UNIT = 7.5; const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); const maxColumnLengths = []; worksheet.eachRow((row, rowNum) => { row.eachCell((cell, num) => { if (typeof cell.value === 'string') { if (maxColumnLengths[num] === undefined) { maxColumnLengths[num] = 0 } const fontSize = cell.font && cell.font.size ? cell.font.size : 11 ctx.font = `${fontSize}pt Calibri` const metrics = ctx.measureText(cell.value) const cellWidth = metrics.width + 20; maxColumnLengths[num] = Math.max(maxColumnLengths[num], cellWidth) } }) }) for (let i = 1; i <= worksheet.columnCount; i++) { const col = worksheet.getColumn(i) const width = maxColumnLengths[i] if (width) { col.width = width / PIXELS_PER_EXCEL_WIDTH_UNIT + 1 } } workbook.xlsx.writeBuffer().then(data => { const blob = new Blob([data], { type: this.blobType }); saveAs(blob, fileName); }); } function download_file(file_id) { window.open('/modulos/general/download_file?id=' + file_id, '_blank'); } function createDataForm ( objData ) { var form = new FormData(); for ( let i in objData ) { form.append( i, objData[i] ); } return form; } $(function() { $( '#btMostrarMasFiltros' ).click( function ( e ) { let _text_more = "More filters"; let _text_less = "Less filters"; e.preventDefault(); var isOpen = $( '#moreFilters' ).hasClass( 'open' ); if ( isOpen ) { $( '#moreFilters' ).removeClass( 'open' ).hide().fadeOut(); $( this ).attr( 'title', _text_more ); $( this ).find( 'i' ).addClass( 'fa-plus-circle' ).removeClass( 'fa-minus-circle' ); } else { $( '#moreFilters' ).addClass( 'open' ).hide().fadeIn(); $( this ).attr( 'title', _text_less ); $( this ).find( 'i' ).removeClass( 'fa-plus-circle' ).addClass( 'fa-minus-circle' ); } }); }); /** * Checks that the input text is only digits * @param selector */ function onlyNumber(selector) { $(selector).each(function( index, e ) { $(e).bind('paste', function (event) { if (event.originalEvent.clipboardData.getData('Text').match(/[^\d]/)) { event.preventDefault(); } }); $(e).bind("keypress", function(event){ if(event.which <= 48 || event.which >=57){ return false; } }); }); } function empty(object) { return (object === undefined || object == ''); } var texto_bdev_service_01 = "Plugin <i>Verifarma Browser Plugin</i> not found. Please verify that it is installed and enabled"; var texto_bdev_service_02 = "Service <i>VerifarmaService</i> not found. Please verify that it is intalled and started on %1:%2 and try again."; var texto_bdev_service_03 = "There is no connection with Integration database. Please check the status, restart the Service <i>VerifarmaService</i> and try again. If the sistem was recently restarted, wait a minute and try again."; var texto_bdev_service_04 = "Information about pending Serial Numbers for pack could not be obtained."; var text_error_general_js = "Please, contact support"; var textErrorRegistroSanitarioNull = "No es posible continuar porque este producto no tiene registro sanitario anvisa incluido en la etiqueta"; var textErrorRegistroSanitarioDifferent = "No es posible continuar porque este producto tiene registrado otro registro sanitario en la etiqueta"; var textErrorRegistroSanitario = "No es posible continuar porque este producto no tiene asociado un registro sanitario en la base de datos";