general.js 13.6 KB
Newer Older
Billy Larru committed
1 2 3 4 5
//DEVELOP
const PATH_GENERAL = 'http://localhost:7070/Asistencia/';
const PATH_IP = 'http://172.16.2.102:7070/Asistencia/';
//PRODUCCION
const PATH_DOMAIN = '';
6
const CODIGO_PROYECTO = '7';
7 8
//const PATH_SERVICIO_REST = 'http://172.16.2.53:8080/security-rest/api/'//'http://app8.sacooliveros.edu.pe:8080/security-rest/api/';
const PATH_SERVICIO_REST = 'http://app9.sacooliveros.edu.pe:8080/security-rest/api/';
9
//<editor-fold> SERVICIOS REST
Billy Larru committed
10

11
const baseURLRest = 'http://sistem16:666/';
12
const baseURLModals = `http://localhost:7070/Asistencia/vistas/modals/`;
13

14
const ajaxWebService = axios.create({
15
	baseURL: baseURLRest
16 17
});
const ajaxModal = axios.create({
18
	baseURL: baseURLModals
19
});
20

Billy Larru committed
21
//<editor-fold>
22
//<editor-fold> MODULO DE POLICIAS
23 24 25 26 27 28 29 30 31 32
const URI_TIPOROL_POLICIA = "tipoRolPolicias";
const URI_FRECUENCIA_ROL_POLICIA = "frecuenciaRolPolicias";
const URI_SEDES = "sedes";
const URI_ESTADO_ASISTENCIA = "estadoAsistencia";
const URI_POLICIAS = "policias";
const URI_ROL_POLICIA = "rolesPolicias";
const URI_POLICIAS_ASISTENCIA = "asistenciaPolicias";
const URI_POLICIA_MONTOS_AMANECIDAS = "montoAmanecidas";
const URI_POLICIA_CONCEPTOSEDES = "conceptoSedes";
const URI_POLICIA_REPORTE_MONTOS = "reporteMontosPolicias";
33
const URI_POLICIA_PROYECCION = "proyeccion";
34
const URI_POLICIA_PROYECTADO_COMPARATIVO = "proyectadoComparativo";
Billy Larru committed
35
const URI_ADMINISTRATIVO_ASISTENCIA = "asistenciaAdministrativa";
36
const URI_TRABAJADORES = "trabajadores";
37 38
const URI_ADMINISTRATIVOS_TOLERANCIA_INDIVIDUAL = "toleranciasIndividuales";
const URI_ADMINISTRATIVOS_ESTADO_TOLERANCIA_INDIVIDUAL = "estadoTolerancias";
39
const URI_ADMINISTRATIVOS_VACACIONES_INDIVIDUAL = "vacacionesAdministrativasIndividuales";
40
const URI_CARGOS = "cargoLaboral";
41 42 43
const URI_DOCENTES_PROGRAMACION_SEMINARIO = "programacionSeminario";
const URI_DOCENTES_TIPO_SEMINARIO = "tipoSeminario";
const URI_DOCENTES_GRUPO_ACADEMICO = "grupoAcademico";
44
const URI_DOCENTES_ASISTENCIAS = "asistenciaDocentes";
45
const URI_ADMINISTRATIVOS_PERIODO_CIERRE_ASISTENCIA = "periodoCierreAsistenciaAdministrativa";
46 47
const URI_ADMINISTRATIVOS_DESCUENTO_MENSUAL = "descuentoMensualAdministrativos";
const URI_ADMINISTRATIVOS_DESCUENTO_MENSUAL_DETALLADO = "descuentoAsistenciaAdministrativaDetallado";
48 49 50 51 52
//</editor-fold>


//</editor-fold>

53 54 55 56 57
swal.mixin({
	buttonsStyling: false,
	confirmButtonClass: 'btn btn-primary mr-5 ml-5',
	cancelButtonClass: 'btn btn-secondary mr-5 ml-5'
});
58 59

$.extend($.fn.dataTable.defaults, {
60
//	bSort: false,
61
	bFilter: false,
62
//	aaSorting: [],
63
	ordering: false,
64 65
	bLengthChange: false,
	bInfo: true,
66
//	paging: true,
67
	iDisplayLength: 20,
68 69 70 71
//	bStateSave: false,
//	autoWidth: false,
//	responsive: true,
//	stateSave: true,
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
	scrollX: true,
	responsive: true,
	language: {
		lengthMenu: "Mostrar: _MENU_",
		zeroRecords: "&nbsp;&nbsp;&nbsp; No se encontraron resultados",
		info: "&nbsp;&nbsp;&nbsp; Mostrando del _START_ al _END_ de un total de _TOTAL_ registros",
		infoEmpty: "&nbsp;&nbsp;&nbsp; Mostrando 0 de 0 registros",
		search: "Filtrar:",
		loadingRecords: "Cargando...",
		processing: '<span style="width:100%;"><img src="http://www.snacklocal.com/images/ajaxload.gif"></span>',
		paginate: {
			first: "First",
			last: "Last",
			next: "Siguiente",
			previous: "Anterior"
		}
	}
89 90
});

91
ajaxWebService.interceptors.response.use(function (response) {
92 93 94 95 96 97
	// Do something with response data
	let respuesta = {
		status: response.data.status || true,
		message: response.data.message || `Operación exitosa`,
		data: response.data.data || response.data
	};
98
//	console.log(respuesta, moment().format("YYYY/DD/MM HH:MM:SS s"))
99
	return respuesta;
100
}, function (error) {
101 102
	// Do something with response error
	return Promise.reject(error);
103 104 105
});


Billy Larru committed
106 107
/*Ajax genral*/
const ajaxRequestSendBody = obj => {
108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127
	let body = JSON.stringify(obj.body);
	return new Promise((resolve, reject) => {
		$.ajax({
			url: obj.url,
			type: obj.type,
			headers: obj.headers,
			data: {body: body},
			beforeSend: (xhr, settings) => {
			}, success: (response, textStatus, jqXHR) => {
				resolve(response)
			}, error: (jqXHR, textStatus, errorThrown) => {
				reject({
					status: jqXHR.status,
					throw: errorThrown || {},
					jqXHR: jqXHR,
					request: obj
				})
			}
		})
	})
Billy Larru committed
128 129 130 131
}
/*Ajax General*/
/*Ajax genral*/
const ajaxRequestGeneral = obj => {
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
	let body = JSON.stringify(obj.body);
	return new Promise((resolve, reject) => {
		$.ajax({
			url: obj.url,
			type: obj.type,
			headers: obj.headers,
			data: {body: body},
			beforeSend: (xhr, settings) => {
			}, success: (response, textStatus, jqXHR) => {
				resolve(response)
			}, error: (jqXHR, textStatus, errorThrown) => {
				reject({
					status: jqXHR.status,
					throw: errorThrown || {},
					jqXHR: jqXHR,
					request: obj
				})
			}
		})
	})
Billy Larru committed
152 153
}
let createSelectOptions = (obj, valueName, textName) => {
154 155 156 157 158
	let options = ''
	obj.forEach((data) => {
		options += ` < option value = "${data[valueName]}" > ${data[textName]} < /option>`
	})
	return options
Billy Larru committed
159 160 161
}

let customSwal = {
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179
	alert(title, text, type) {
		let colors = {
			success: '#66BB6A',
			error: '#EF5350',
			warning: '#FF7043'
		}
		let btnColor = colors[type]
		return new Promise((resolve, reject) => {
			swal({
				title: title,
				text: text,
				confirmButtonColor: btnColor,
				type: type
			}, (isConfirm) => {
				resolve()
			})
		})
	}
Billy Larru committed
180 181 182 183 184 185 186 187 188 189 190
}

/**
 * Get the closest matching element up the DOM tree.
 * @private
 * @param  {Element} elem     Starting element
 * @param  {String}  selector Selector to match against
 * @return {Boolean|Element}  Returns null if not match found
 */
let getClosest = (elem, selector) => {

191
// Element.matches() polyfill
192 193
	if (!Element.prototype.matches) {
		Element.prototype.matches =
194 195 196 197 198 199 200 201 202 203 204 205
			Element.prototype.matchesSelector ||
			Element.prototype.mozMatchesSelector ||
			Element.prototype.msMatchesSelector ||
			Element.prototype.oMatchesSelector ||
			Element.prototype.webkitMatchesSelector ||
			function (s) {
				var matches = (this.document || this.ownerDocument).querySelectorAll(s),
					i = matches.length
				while (--i >= 0 && matches.item(i) !== this) {
				}
				return i > -1
			}
206
	}
207
// Get closest match
208 209 210 211 212
	for (; elem && elem !== document; elem = elem.parentNode) {
		if (elem.matches(selector))
			return elem
	}
	return null
Billy Larru committed
213 214
}
let block = () => {
215 216 217 218 219 220 221 222 223 224 225 226 227 228 229
	$.blockUI({
		message: '<i class="icon-spinner4 spinner"></i>',
		timeout: 2000, //unblock after 2 seconds
		overlayCSS: {
			backgroundColor: '#1b2024',
			opacity: 0.8,
			cursor: 'wait'
		},
		css: {
			border: 0,
			color: '#fff',
			padding: 0,
			backgroundColor: 'transparent'
		}
	});
Billy Larru committed
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
}
//let logOut = () =>{
//    document.querySelector('#logOut').addEventListener('click', (e) => {
//        window.location.href = 'http://172.16.2.53:8080/proyecto-estandar/vistas/logout'
//    })
//}
//logOut();

//let logOut = () => {
//    $('.logOut').click(function () {
//        console.log("redireccionando")
//        window.location.href = CONSTANTES.PATH_IP + 'vistas/logout';
//    })
//}

let logOut = () => {
246
	document.querySelector('#logOut').addEventListener('click', (e) => {
247
		window.location.href = `${contextPath}/vistas/logout`;
248
	});
249 250
};
function defaultConfigDatePicker() {
251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278
	$('.datepicker').datepicker({
		dateFormat: 'dd/mm/yy',
		showButtonPanel: true,
		changeMonth: true,
		changeYear: true,
		minDate: '-4Y',
		maxDate: '+1Y',
		inline: true
	});
	$.datepicker.regional['es'] = {
		closeText: 'Cerrar',
		prevText: '<Ant',
		nextText: 'Sig>',
		currentText: 'Hoy',
		monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Setiembre', 'Octubre', 'Noviembre', 'Diciembre'],
		monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
		dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
		dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mie', 'Jue', 'Vie', 'Sáb'],
		dayNamesMin: ['Do', 'Lu', 'Ma', 'Mi', 'Ju', 'Vi', 'Sá'],
		weekHeader: 'Sm',
		dateFormat: 'dd/mm/yy',
		firstDay: 1,
		isRTL: false,
		showMonthAfterYear: false,
		yearSuffix: ''
	};
	$.datepicker.setDefaults($.datepicker.regional['es']);
	;
279 280 281
}


282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297
//function defaultConfigDateRangePicker() {
//    $('.daterange-basic').daterangepicker({
//        applyClass: 'bg-slate-600',
////        "singleDatePicker": true,
//        cancelClass: 'btn-default',
////        showDropdowns: false,
////        timePicker: true,
////        opens: 'center',
////        singleDatePicker: true,
//        autoApply: true,
//        locale: {
//            format: 'DD/MM/YYYY'
//        }
//    });
////    $('.calendar.right').hide();
//}
298

299

300 301 302


(function (a) {
303 304 305 306 307 308
	a.fn.validCampo = function (b) {
		a(this).on({keypress: function (a) {
				var c = a.which, d = a.keyCode, e = String.fromCharCode(c).toLowerCase(), f = b;
				(-1 != f.indexOf(e) || 9 == d || 37 != c && 37 == d || 39 == d && 39 != c || 8 == d || 46 == d && 46 != c) && 161 != c || a.preventDefault()
			}})
	}
309
})(jQuery);
310
function primeraLetraMayuscula(str) {
311 312 313 314
	let strLower = str.toLowerCase();
	let caracter = strLower.substr(0, 1).toUpperCase();
	let cadena = caracter + strLower.substr(1);
	return cadena;
315 316 317 318
}



Billy Larru committed
319
const makeDatatable = (
320 321 322 323 324 325 326 327 328
	wrapName = ``,
	forDatatable = {
	data: [],
		columns: [],
		footerFilter: false,
		footer: false
	},
	className = ``,
	) => {
Billy Larru committed
329 330 331 332 333 334 335 336 337 338 339 340 341
	if (!wrapName) {
		return {
			message: `{wrapName} is empty`,
			status: false
		}
	}

	if (forDatatable.columns.length <= 0) {
		return {
			message: `{columns} is empty`,
			status: false
		}
	}
342

Billy Larru committed
343
	let nameDatatable = `${wrapName}-datatable`;
344

Billy Larru committed
345
	// table
346
	let table_head = `
Billy Larru committed
347 348 349
		<table id="${nameDatatable}" class="table table-hover ${className}" cellspacing="0" width="100%">`;

	// headers
350
	let table_head_th = `
351 352
		<thead>
			<tr>`;
Billy Larru committed
353
	forDatatable.columns.forEach((obj) => {
354 355 356 357 358 359 360
		let title = `undefined`;
		if (obj.title) {
			title = obj.title;
		} else if (obj.data) {
			title = obj.data;
		}
		table_head_th += `
361
			<th>${title}</th>`
362 363
	})
	table_head_th += `
364 365 366
			</tr>
		</thead>`

Billy Larru committed
367
	// footers
368
	let table_foot_th = ``;
Billy Larru committed
369
	if (forDatatable.footer) {
370
		table_foot_th = `
371 372
			<tfoot>
				<tr>`;
Billy Larru committed
373
		forDatatable.columns.forEach((obj) => {
374 375 376 377 378 379 380
			let title = `undefined`;
			if (obj.title) {
				title = obj.title;
			} else if (obj.data) {
				title = obj.data;
			}
			table_foot_th += `
381
				<th>${title}</th>`
382 383
		})
		table_foot_th += `
384 385 386
				</tr>
			</tfoot>
		`
387
	}
388

Billy Larru committed
389
	// table
390
	let table_foot = `</table>`
391

Billy Larru committed
392 393 394 395
	$(`#${wrapName}`).empty().append(`${table_head}${table_head_th}${table_foot_th}${table_foot}`);

	if (forDatatable.footerFilter) {
		// Setup - add a text input to each footer cell
396 397 398 399 400 401 402
		$(`#${nameDatatable} tfoot th`).each(function () {
			var title = $(this).text();
			$(this).html(`<input type="text" class="form-control" placeholder="${title}" />`);
		});
	}

	$(`#${nameDatatable}`)
403
		.DataTable(forDatatable);
Billy Larru committed
404 405 406

	if (forDatatable.footerFilter) {
		// DataTable
407
		let table = $(`#${nameDatatable}`).DataTable();
Billy Larru committed
408

409 410 411 412 413 414
		// Apply the search
		table.columns().every(function () {
			var that = this;
			$('input', this.footer()).on('keyup change', function () {
				if (that.search() !== this.value) {
					that
415 416
						.search(this.value)
						.draw();
417 418 419 420
				}
			});
		});

Billy Larru committed
421
		$(`#${wrapName} .dataTables_scrollBody`).appendTo(`#${wrapName} .dataTables_scroll`);
422 423 424 425
	}

	return Promise.resolve({
		datatable: $(`#${nameDatatable}`),
Billy Larru committed
426
		container: $(`#${wrapName}`)
427
	});
428 429 430 431 432
}



const randomIntFromInterval = (minimum, maximum) => {
433
	return Math.round(Math.random() * (maximum - minimum) + minimum);
434 435
}

436
const cleanQueryParams = (params = {}) => {
437 438 439 440 441 442 443 444 445
	for (var key in params) {
		if (params.hasOwnProperty(key)) {
			if (!params[key]) {
				delete params[key];
			}
		}
	}

	return params;
446 447 448 449 450
}

let initDatePicker = (...selectorName) => {
	selectorName.forEach(id => {
		let options = {
451
			format: "dd/mm/yyyy",
452
			zIndexOffset: 3000,
453 454
			autoclose: true,
			language: "es",
455 456 457 458 459 460 461 462
			onSelect: function () {
//        $(this).valid();
			}
		}
		$(id).datepicker(options);
		$(id).datepicker('setDate', 'now');
	});

463 464
}

465
const initSelect2 = (nodeIdentifier, URI, {title, subtitle} = {}) => {
466 467 468
	$(`${nodeIdentifier}`).select2({
		containerCssClass: 'select-xs',
		ajax: {
469
			url: URI,
470 471 472 473 474 475 476 477
			dataType: `json`,
			delay: 1000,
			data: function (params) {
				return {
					q: params.term, // search term
					page: params.page
				};
			},
478
			processResults: function (data, params) {
479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507
				// parse the results into the format expected by Select2
				// since we are using custom formatting functions we do not need to
				// alter the remote JSON data, except to indicate that infinite
				// scrolling can be used
				params.page = params.page || 1;

				return {
					results: data,
					pagination: {
						more: (params.page * 30) < data.length
					}
				};
			},
			cache: true
		},
		placeholder: `Buscar`,
		allowClear: true,
		escapeMarkup: function (markup) {
			return markup;
		}, // let our custom formatter work
		minimumInputLength: 1,
		templateResult: formatRepo,
		templateSelection: formatRepoSelection
	});

	function formatRepo(repo) {
		if (repo.loading) {
			return repo.text;
		}
508

509 510
		var markup = `
			<div class='select2-result-repository clearfix'>
511
				<div class='select2-result-repository__title'>${repo[title]}</div>`;
512 513
		markup += `
				<div class='select2-result-repository__statistics'>
514
					<div class='select2-result-repository__forks'>${repo[subtitle]}</div>					
515 516 517 518 519 520
				</div>		
			</div>`

		return markup;
	}

521
	function formatRepoSelection(repo) {
522
		if (repo.id) {
523
			return repo[title];
524 525 526
		} else {
			return repo.text;
		}
527
}
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
}



const generarFechas = (desde, hasta) => {
	let reverseDesde = desde.split("/").reverse().join("/");
	let reverseHasta = hasta.split("/").reverse().join("/");
	desde = moment(reverseDesde);
	hasta = moment(reverseHasta);
	let diaActual = desde;

	let fechas = [];
	while (diaActual.isSameOrBefore(hasta)) {
		fechas.push(diaActual.format('DD/MM/YYYY'));
		diaActual.add(1, 'days');
	}
	return fechas;
545 546 547
}