general.js 12.9 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 12
const baseURLRest = 'http://sistem16:666/';

13
const ajaxWebService = axios.create({
14
	baseURL: baseURLRest
15 16
});
const ajaxModal = axios.create({
17
	baseURL: `http://localhost:7070/Asistencia/vistas/modals/`
18
});
19

Billy Larru committed
20
//<editor-fold>
21
//<editor-fold> MODULO DE POLICIAS
22 23 24 25 26 27 28 29 30 31
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";
32
const URI_POLICIA_PROYECCION = "proyeccion";
33
const URI_POLICIA_PROYECTADO_COMPARATIVO = "proyectadoComparativo";
Billy Larru committed
34
const URI_ADMINISTRATIVO_ASISTENCIA = "asistenciaAdministrativa";
35
const URI_TRABAJADORES = "trabajadores";
36 37
const URI_ADMINISTRATIVOS_TOLERANCIA_INDIVIDUAL = "toleranciasIndividuales";
const URI_ADMINISTRATIVOS_ESTADO_TOLERANCIA_INDIVIDUAL = "estadoTolerancias";
38 39 40 41 42
//</editor-fold>


//</editor-fold>

43 44 45 46 47
swal.mixin({
	buttonsStyling: false,
	confirmButtonClass: 'btn btn-primary mr-5 ml-5',
	cancelButtonClass: 'btn btn-secondary mr-5 ml-5'
});
48 49

$.extend($.fn.dataTable.defaults, {
50
//	bSort: false,
51
	bFilter: false,
52 53
//	aaSorting: [],
//	ordering: false,
54 55
	bLengthChange: false,
	bInfo: true,
56
//	paging: true,
57
	iDisplayLength: 20,
58 59 60 61
//	bStateSave: false,
//	autoWidth: false,
//	responsive: true,
//	stateSave: true,
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
	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"
		}
	}
79 80
});

81
ajaxWebService.interceptors.response.use(function (response) {
82 83 84 85 86 87
	// 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
	};
88
//	console.log(respuesta, moment().format("YYYY/DD/MM HH:MM:SS s"))
89
	return respuesta;
90
}, function (error) {
91 92
	// Do something with response error
	return Promise.reject(error);
93 94 95
});


Billy Larru committed
96 97
/*Ajax genral*/
const ajaxRequestSendBody = obj => {
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
	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
118 119 120 121
}
/*Ajax General*/
/*Ajax genral*/
const ajaxRequestGeneral = obj => {
122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
	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
142 143
}
let createSelectOptions = (obj, valueName, textName) => {
144 145 146 147 148
	let options = ''
	obj.forEach((data) => {
		options += ` < option value = "${data[valueName]}" > ${data[textName]} < /option>`
	})
	return options
Billy Larru committed
149 150 151
}

let customSwal = {
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
	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
170 171 172 173 174 175 176 177 178 179 180
}

/**
 * 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) => {

181
// Element.matches() polyfill
182 183
	if (!Element.prototype.matches) {
		Element.prototype.matches =
184 185 186 187 188 189 190 191 192 193 194 195
			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
			}
196
	}
197
// Get closest match
198 199 200 201 202
	for (; elem && elem !== document; elem = elem.parentNode) {
		if (elem.matches(selector))
			return elem
	}
	return null
Billy Larru committed
203 204
}
let block = () => {
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219
	$.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
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
}
//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 = () => {
236 237 238
	document.querySelector('#logOut').addEventListener('click', (e) => {
		window.location.href = '../vistas/logout';
	});
239 240
};
function defaultConfigDatePicker() {
241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268
	$('.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']);
	;
269 270 271
}


272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
//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();
//}
288

289

290 291 292


(function (a) {
293 294 295 296 297 298
	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()
			}})
	}
299
})(jQuery);
300
function primeraLetraMayuscula(str) {
301 302 303 304
	let strLower = str.toLowerCase();
	let caracter = strLower.substr(0, 1).toUpperCase();
	let cadena = caracter + strLower.substr(1);
	return cadena;
305 306 307 308
}



Billy Larru committed
309
const makeDatatable = (
310 311 312 313 314 315 316 317 318
	wrapName = ``,
	forDatatable = {
	data: [],
		columns: [],
		footerFilter: false,
		footer: false
	},
	className = ``,
	) => {
Billy Larru committed
319 320 321 322 323 324 325 326 327 328 329 330 331
	if (!wrapName) {
		return {
			message: `{wrapName} is empty`,
			status: false
		}
	}

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

Billy Larru committed
333
	let nameDatatable = `${wrapName}-datatable`;
334

Billy Larru committed
335
	// table
336
	let table_head = `
Billy Larru committed
337 338 339
		<table id="${nameDatatable}" class="table table-hover ${className}" cellspacing="0" width="100%">`;

	// headers
340
	let table_head_th = `
341 342
		<thead>
			<tr>`;
Billy Larru committed
343
	forDatatable.columns.forEach((obj) => {
344 345 346 347 348 349 350
		let title = `undefined`;
		if (obj.title) {
			title = obj.title;
		} else if (obj.data) {
			title = obj.data;
		}
		table_head_th += `
351
			<th>${title}</th>`
352 353
	})
	table_head_th += `
354 355 356
			</tr>
		</thead>`

Billy Larru committed
357
	// footers
358
	let table_foot_th = ``;
Billy Larru committed
359
	if (forDatatable.footer) {
360
		table_foot_th = `
361 362
			<tfoot>
				<tr>`;
Billy Larru committed
363
		forDatatable.columns.forEach((obj) => {
364 365 366 367 368 369 370
			let title = `undefined`;
			if (obj.title) {
				title = obj.title;
			} else if (obj.data) {
				title = obj.data;
			}
			table_foot_th += `
371
				<th>${title}</th>`
372 373
		})
		table_foot_th += `
374 375 376
				</tr>
			</tfoot>
		`
377
	}
378

Billy Larru committed
379
	// table
380
	let table_foot = `</table>`
381

Billy Larru committed
382 383 384 385
	$(`#${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
386 387 388 389 390 391 392
		$(`#${nameDatatable} tfoot th`).each(function () {
			var title = $(this).text();
			$(this).html(`<input type="text" class="form-control" placeholder="${title}" />`);
		});
	}

	$(`#${nameDatatable}`)
393
		.DataTable(forDatatable);
Billy Larru committed
394 395 396

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

399 400 401 402 403 404
		// Apply the search
		table.columns().every(function () {
			var that = this;
			$('input', this.footer()).on('keyup change', function () {
				if (that.search() !== this.value) {
					that
405 406
						.search(this.value)
						.draw();
407 408 409 410
				}
			});
		});

Billy Larru committed
411
		$(`#${wrapName} .dataTables_scrollBody`).appendTo(`#${wrapName} .dataTables_scroll`);
412 413 414 415
	}

	return Promise.resolve({
		datatable: $(`#${nameDatatable}`),
Billy Larru committed
416
		container: $(`#${wrapName}`)
417
	});
418 419 420 421 422
}



const randomIntFromInterval = (minimum, maximum) => {
423
	return Math.round(Math.random() * (maximum - minimum) + minimum);
424 425
}

426
const cleanQueryParams = (params = {}) => {
427 428 429 430 431 432 433 434 435
	for (var key in params) {
		if (params.hasOwnProperty(key)) {
			if (!params[key]) {
				delete params[key];
			}
		}
	}

	return params;
436 437 438 439 440
}

let initDatePicker = (...selectorName) => {
	selectorName.forEach(id => {
		let options = {
441
			format: "dd/mm/yyyy",
442
			zIndexOffset: 3000,
443 444
			autoclose: true,
			language: "es",
445 446 447 448 449 450 451 452
			onSelect: function () {
//        $(this).valid();
			}
		}
		$(id).datepicker(options);
		$(id).datepicker('setDate', 'now');
	});

453 454
}

455 456
const initSelect2 = (nodeIdentifier, URI, {title, subtitle} = {}) => {
	console.log(2)
457 458 459
	$(`${nodeIdentifier}`).select2({
		containerCssClass: 'select-xs',
		ajax: {
460
			url: URI,
461 462 463 464 465 466 467 468
			dataType: `json`,
			delay: 1000,
			data: function (params) {
				return {
					q: params.term, // search term
					page: params.page
				};
			},
469
			processResults: function (data, params) {
470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498
				// 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;
		}
499

500 501
		var markup = `
			<div class='select2-result-repository clearfix'>
502
				<div class='select2-result-repository__title'>${repo[title]}</div>`;
503 504
		markup += `
				<div class='select2-result-repository__statistics'>
505
					<div class='select2-result-repository__forks'>${repo[subtitle]}</div>					
506 507 508 509 510 511
				</div>		
			</div>`

		return markup;
	}

512
	function formatRepoSelection(repo) {
513
		if (repo.id) {
514
			return repo[title];
515 516 517
		} else {
			return repo.text;
		}
518
}
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
}



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;
536 537 538
}