');
}); //each
$('#lista-puestos option:first-child').attr("selected", "selected");
$('#lista-puestos').trigger('change'); //Notifico
});
}, //changeContrato
changePuesto: function () {
// $('#bloque_controles_puesto').hide();
$('#bloque_detalles_puesto').hide();//gonzalo
// $('#contenedor-video').hide();//gonzalo
// $('#PresentaEnlaceYoutube').hide();
// $('#PresentaFoto').hide();
var that=this;
var idcontrato=$('#inicio_listado_contratos_por_provincia').val();
if (getUrlParameter('puesto'))
$('#lista-puestos').val(getUrlParameter('puesto'));// Gonzalo
var idpuesto=$('#lista-puestos').val();
if(!idcontrato || (!idpuesto))
return;
var contrato = _.where(this.ListaContratos,{idcontrato: idcontrato});//Underscore where devuelve un array, como no debería haber mas que uno cojo el elemento 0.
var puesto = _.where(this.ListaPuestos,{idpuesto: idpuesto});//Underscore where devuelve un array, como no debería haber mas que uno cojo el elemento 0.
puestoText = puesto[0].PresentaTexto;
//Está asociado y registrado si tiene registro en el sistema y además los campos de aceptación del usuario y admin del contrato tienen una fecha
/*var RegistradoYAsociado=((contrato[0].AceptadoUsuario?contrato[0].AceptadoUsuario:'').length==8
&&
(contrato[0].AceptadoAdmin?contrato[0].AceptadoAdmin:'').length==8);
//Segunda vuelta, un usuario también está registrado y asociado si es un super admin o el administrador del contrato.
RegistradoYAsociado=RegistradoYAsociado
|| false
|| (contrato[0].idusuariotitular==-1);
*/
Registrado = false;
// $('#PresentaTexto').html(puesto[0].PresentaTexto);
if(puesto[0].PagoUnico==0)
$('#preciominuto').html('NOTA INFORMATIVA: El coste por minuto de atención para este puesto es de
'+puesto[0].preciominuto+' créditos.');//gonzalo
else $('#preciominuto').html('NOTA INFORMATIVA: El coste de atención para este puesto es un pago único de
'+puesto[0].preciominuto+' créditos.');
//$('#HoraApertura').html(puesto[0].HoraApertura);//gonzalo
if ((puesto[0].PresentaFoto) && ((puesto[0].PresentaFoto?puesto[0].PresentaFoto:'').length>0)) {
// $('#PresentaFoto').load(function(){$(this).show()}).attr("src", puesto[0].PresentaFoto); //Para que no se note el salto de una imagen a otra
// $('#PresentaFoto').show();
} else {
// $('#PresentaFoto').hide();
// $('#PresentaFoto').prop('src','');
}
if ((puesto[0].PresentaEnlaceYoutube) && ((puesto[0].PresentaEnlaceYoutube?puesto[0].PresentaEnlaceYoutube:'').length>0)) {
// $('#PresentaEnlaceYoutube').load(function(){$(this).show()}).attr("src", createVideoURLEmbedded(puesto[0].PresentaEnlaceYoutube));//Para que no se vea el paso de un src='' a uno con video
// $('#contenedor-video').show();//gonzalo
} else {
// $('#contenedor-video').hide();//gonzalo
// $('#PresentaEnlaceYoutube').prop('src','');//Para que no siga sonando por detrás
// $('#PresentaEnlaceYoutube').hide();
}
//Si no acepta no registrados y asociados, y el usuario no está registrado y asociado le dejo ahí sin mostrar controles de puesto
if ( (contrato[0].AceptaUsuariosNoRegistrados!=1) && !(Registrado)) {
$('#puesto-boton-PedirCita').hide();
$('#puesto-boton-PedirCita').parent().hide();
$('#puesto-boton-AtencionInmediata').hide();
$('#puesto-boton-AtencionInmediata').parent().hide();
$('#puesto-boton-Reserva').hide();//edu
$('#Presencial').parent().hide();
$('#Telefonica').parent().hide();
$('#Videoconferencia').parent().hide();
$('#Multicita').parent().hide();//edu
} else {//o el contrato acepta no registrados, o no los acepta pero este usuario está asociado a ese contrato
if (puesto[0].AceptaLlamadas>0) {
$('#Telefonica').prop('checked',true).parent().show();
$('#Multicita').removeAttr('checked');//edu
$('#Multicita').parent().hide();//edu
$('#puesto-boton-Reserva').hide();//edu
} else $('#Telefonica').parent().hide();
if (puesto[0].AceptaPresencial>0) {
$('#Telefonica').removeAttr('checked');
$('#Presencial').prop('checked',true).parent().show();
$('#Multicita').removeAttr('checked');//edu
$('#Multicita').parent().hide();//edu
$('#puesto-boton-Reserva').hide();//edu
} else $('#Presencial').parent().hide();
if (puesto[0].AceptaChat>0) {
$('#Telefonica').removeAttr('checked');
$('#Presencial').removeAttr('checked');
$('#Chat').prop('checked',true).parent().show();
$('#Multicita').removeAttr('checked');//edu
$('#Multicita').parent().hide();//edu
$('#puesto-boton-Reserva').hide();//edu
} else $('#Chat').parent().hide();
if (puesto[0].AceptaVideoconferencia>0) {
$('#Telefonica').removeAttr('checked');
$('#Presencial').removeAttr('checked');
$('#Chat').removeAttr('checked');
$('#Videoconferencia').prop('checked',true).parent().show();
$('#Multicita').removeAttr('checked');//edu
$('#Multicita').parent().hide();//edu
$('#puesto-boton-Reserva').hide();//edu
} else $('#Videoconferencia').parent().hide();
$('#puesto-boton-PedirCita').hide();
$('#puesto-boton-PedirCita').parent().hide();
$('#puesto-boton-AtencionInmediata').hide();
$('#puesto-boton-AtencionInmediata').parent().hide();
if((puesto[0].AceptaLlamadas>0) || (puesto[0].AceptaPresencial>0) || (puesto[0].AceptaVideoconferencia>0) || (puesto[0].AceptaChat > 0)) { //Tiene que tener al menos un tipo de atención
if (puesto[0].AceptaCitas>0) {
$('#puesto-boton-PedirCita').show();
$('#puesto-boton-PedirCita').parent().show();
}
$('#puesto-boton-AtencionInmediata').show();
$('#puesto-boton-AtencionInmediata').parent().show();
}
if (puesto[0].AceptaMulticita>0) {
$('#Telefonica').removeAttr('checked');
$('#Presencial').removeAttr('checked');
$('#Videoconferencia').removeAttr('checked');
$('#Telefonica').parent().hide();
$('#Presencial').parent().hide();
$('#Videoconferencia').parent().hide();
$('#puesto-boton-PedirCita').hide();
$('#puesto-boton-PedirCita').parent().hide();
$('#puesto-boton-AtencionInmediata').hide();
$('#puesto-boton-AtencionInmediata').parent().hide();
$('#Multicita').prop('checked',true).parent().hide();
var reservasAdmitidas = puesto[0].MulticitaMaxReservas;
var contadorReservas=0;
var url="rest/data.php/citas_puesto_reservas/"+idpuesto;
$('#puesto-boton-Reserva').prop('disabled', true);
$('#puesto-boton-Reserva').show();
//RICARDO 2018-2 Pedía un listado de ids de citas y aquí las contaba, cambiado
$.getJSON( url, function(data) {
var contadorReservas=parseInt(data['contadorReservas']);
if (contadorReservas >= reservasAdmitidas){
$('#mensajenocredito').html('
Lo sentimos, se han agotado las plazas.');
$('#puesto-boton-Reserva').prop('disabled', true);
}
});
} else {
$('#puesto-boton-Reserva').hide();
$('#Multicita').parent().hide();
}
if (puesto[0].Estado==0) { //ONLINE
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-AtencionInmediata').prop('disabled', false);
} else if (puesto[0].Estado==1) {//OCUPADO
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-AtencionInmediata').prop('disabled', true);
} else if (puesto[0].Estado==2) {//OFFLINE
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-AtencionInmediata').prop('disabled', true);
}
$('#bloque_controles_puesto').show();//Muestro el bloque de controles una vez configurados
$('#bloque_detalles_puesto').show();//gonzlo
//Asigno los eventos de pedir cita y atención inmediata
$('#puesto-boton-PedirCita').off('click');
$('#puesto-boton-PedirCita').on('click', function () {
tipocita=$('input[name="tipocita"]:checked').val();
$.getJSON("rest/data.php/getCurrentPlatformTime", function(currentTime) {
getCitasPuesto(puesto[0], currentTime, tipocita, true);
});
$('#ModalCitaTitle').text('Cita');
switch( tipocita ) {
case "1" :
$('#ModalCitaTitle').text('Cita Presencial');
break;
case "2" :
$('#ModalCitaTitle').text('Cita Telefónica');
break;
case "3" :
$('#ModalCitaTitle').text('Cita Videoconferencia');
break;
case "5" :
$('#ModalCitaTitle').text('Cita Chat');
break;
}
$('#ModalCita').modal('show');
});
$('#puesto-boton-AtencionInmediata').off('click');
$('#puesto-boton-AtencionInmediata').on('click', function () {
tipocita=$('input[name="tipocita"]:checked').val();
$.getJSON("rest/data.php/getCurrentPlatformTime", function(currentTime) {
getCitasPuesto(puesto[0], currentTime, tipocita, false);
});
var titulotipo='';
switch( tipocita ) {
case "1" :
titulotipo='Presencial';
break;
case "2" :
titulotipo='Telefónica';
break;
case "3" :
titulotipo='Videoconferencia';
break;
case "5" :
titulotipo='Chat';
break;
}
var titulo='Atención inmediata - '+titulotipo;
$('#ModalCitaTitle').text(titulo);
$('#ModalCita').modal('show');
});
/*ini multicita*/
$('#puesto-boton-Reserva').off('click');
$('#puesto-boton-Reserva').on('click', function () {
tipocita=$('input[name="tipocita"]:checked').val();
$.getJSON("rest/data.php/getCurrentPlatformTime", function(currentTime) {
getCitasPuesto(puesto[0], currentTime, tipocita, false);
});
if(tipocita == 4){
var titulo='Multicita - ' + puesto[0].PresentaTexto;
}
$('#ModalCitaTitle').text(titulo);
$('#ModalCita').modal('show');
});
}
if ( 0 < (puesto[0].preciominuto ) ){
$('#mensajenocredito').html('
En estos momentos no dispone de créditos suficientes para solicitar citas. Acceda a su cuenta o compre créditos.');
$('#puesto-boton-AtencionInmediata').prop('disabled', true).html("Atención Inmediata
No Disponible");
$('#puesto-boton-PedirCita').prop('disabled', true);
$('#puesto-boton-Reserva').prop('disabled', true);
}else{
$('#mensajenocredito').html('') ;
$('#puesto-boton-AtencionInmediata').prop('disabled', false);
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-Reserva').prop('disabled', false);
// Si el estado es ocupado y offline ponen el mensaje de no disponible en web Javi y Jorge 12062020 19:58
if (puesto[0].Estado == 0) {
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-AtencionInmediata').prop('disabled', false).html("Atención Inmediata");
} else if (puesto[0].Estado == 1) {
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-AtencionInmediata').prop('disabled', true).html("Atención Inmediata
No Disponible");
} else if (puesto[0].Estado == 2) {
$('#puesto-boton-PedirCita').prop('disabled', false);
$('#puesto-boton-AtencionInmediata').prop('disabled', true).html("Atención Inmediata
No Disponible");
}
}
},//changePuesto
});
var inicioListaContratosView = new InicioListaContratosView();
//MISDATOS-----------------------------------------------------------------------------------------------------------------------
//VISTA MisDatos
var MisDatosView = Backbone.View.extend({
el_mis_datos:'#contenedor_misdatos',
render: function (options) {
this.setElement(this.el_mis_datos);
this.idusuario=options.idusuario;
//Pongo el cargando por si tarda el servidor en responder
var template = _.template($('#Template-Loading').html(), {});
this.$el.html(template);
//La funciones success,error,etc son anónimas, y this solo tiene sentido hasta este contexto (para acceder desde success, error y demás al objeto this)
//Al llamar a asincronos (por ejemplo el fetch) las respuestas no están en su ámbito
var that = this;
if (options.idusuario>0) { //El usuario está registrado
var misdatos = new MisDatos({idusuario: options.idusuario});
misdatos.fetch({
success: function (misdatos,response) {
var template = _.template($('#Template-MisDatos').html(), {misdatos : misdatos});
that.$el.html(template);
that.PrepararFormulario();//Cargo todo lo que necesite el formulario
},
error: function (misdatos,response) {
var errortext=response.responseText;
if (errortext.length<=0)
errortext='error: No se ha recibido nada';
var template = _.template($('#Template-Error').html(), {error : errortext});
that.$el.html(template);
}
});
} else { //Le muestro para registrarse
//MIS DATOS
var template = _.template($('#Template-MisDatos').html(), {misdatos : null});
that.$el.html(template);
this.PrepararFormulario();//Cargo todo lo que necesite el formulario
}
}, //FIN RENDER
GuardarMisDatos: function () {
//Le indico que está guardando
$('#FormMisDatos').find(':submit').html('Guardando, espere por favor...');
var misdatosDetails = $('#FormMisDatos').serializeObject();//currentTarget es el form, es el objetivo del evento
var misdatos = new MisDatos({idusuario: this.idusuario});
var that=this;
misdatos.save(misdatosDetails, {
success: function (usuario,response) {
console.log('register_success');
if ((that.idusuario<=0) || !(that.idusuario)) { //Es nuevo
bootbox.dialog({message: "Se ha dado correctamente de alta, por favor, siga las instrucciones en el correo que recibirá para activar su cuenta", title: "Información",
buttons: {
success: {
label: "Aceptar",
className: "btn-success",
callback: function() {
location.reload();
}
},
}
});
} else {
CargaMisDatos();
}
},
error: function (usuario,response) {
console.log('register_failed');
$('#FormMisDatos').find('div[id="Mensaje"]').html(response.responseText);
$('#FormMisDatos').find('div[id="Mensaje"]').show().removeClass('hidden');
$('#FormMisDatos').find(':submit').html('Registrarme');
}
});
return false;
}, //GuardarMisDatos
PrepararFormulario: function () {
// Aquí cargo los requisitos y todo lo que lleve el formulario
//Cuelgo el plugin de date picker
var that=this;
$('#FechaNacimiento').datetimepicker({
lang:'es',
timepicker:false,
format:'d/m/Y'
});
//Validar el formulario
$("#FormMisDatos").on('submit', function (e){
//Evito que mande el formulario
e.preventDefault();//En realidad no mando el formulario, serializo su contenido y lo mando con backbone/ajax
});
$("#pedirCitaButton").unbind();
$("#pedirCitaButton").click(function(e) {
e.preventDefault();
var formIncident = $("#FormIncident").serializeObject();
if (formIncident['idcontrato'] <= 0) {
$("div#respondInFourtyEight div.alert-danger").show();
$("div#respondInFourtyEight div.alert-danger").html("Por favor seleccione el departamento.");
setTimeout(function() {
$("div#respondInFourtyEight div.alert-danger").hide();
}, 5000);
return;
}
$respondTime = 48;
$.ajax({
url: 'https://segovia.atencionciudadana.es/rest/data.php/get_respond_time/' + formIncident['idcontrato'],
type: 'GET',
success: function(data) {
data = JSON.parse(data);
if (parseInt(data['RespondTime']) > 0)
$respondTime = parseInt(data['RespondTime']);
formIncident['idusuario'] = that.idusuario;
formIncident['respondTime'] = $respondTime;
formIncident['fechaprevistafin'] = "NULL";
formIncident['estado'] = '0';
formIncident['gmtValue'] = $("#SelectGMTIncident option:selected").val();
var attachmentFilePath = $("#selIncidentFile").val();
var attachmentFileSplit = attachmentFilePath.split("\\");
var attachmentFileName = attachmentFileSplit[attachmentFileSplit.length - 1];
formIncident['documentsenciados'] = attachmentFileName;
var file_data = $('#selIncidentFile').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://segovia.atencionciudadana.es/rest/data.php/upload',
// url: 'https://segovia.atencionciudadana.es/upload.php',
type: "POST",
data: form_data,
contentType: false,
cache: false,
processData:false,
success: function(data) {
var incident = new Incident();
incident.save(formIncident, {
success: function(incident, response) {
$("div#respondInFourtyEight div.alert-success").show();
document.getElementById("FormIncident").reset();
$("label[for='selIncidentFile']").html('Select a file');
setTimeout(function() {
$("div#respondInFourtyEight div.alert-success").hide();
}, 2000);
},
error: function(incident, error) {
//$("div#respondInFourtyEight div.alert-success").show();
//document.getElementById("FormIncident").reset();
//$("label[for='selIncidentFile']").html('Select a file');
$("div#respondInFourtyEight div.alert-danger").show();
setTimeout(function() {
$("div#respondInFourtyEight div.alert-danger").hide();
// $("div#respondInFourtyEight div.alert-success").hide();
}, 2000);
}
});
},
error: function(error) {
console.log(error);
}
});
}
});
});
$.validator.methods.date = function(value, element) {
return this.optional(element) || (parseUserDate(value) !== null);
};
//updated for encryption
var knowIfValidarPass = true;
if(document.getElementById("captcha_image") === null){
if(document.getElementById("Pass").value.length == 0){
knowIfValidarPass = false;
}
}
$("#FormMisDatos").validate({
errorLabelContainer: "#FormMisDatos #Mensaje",
wrapper: "li",
rules: {
Nombre: {
required:true,
maxlength:50
},
Apellido1: {
required:false,
maxlength:50
},
Apellido2: {
required:false,
maxlength:50
},
NIFCIFPASS: {
required:false,
maxlength:9
},
TipoNIFCIFPASS: {
required:false,
},
NombreEmpresa: {
maxlength:150
},
FechaNacimiento: {
required: false,
date: true,
},
Telefonos: {
required:true,
},
Email: {
required: true,
email: true,
maxlength:100
},
Pass: {
required: knowIfValidarPass,
maxlength:30,
minlength: 6
},
DirNacimiento_idpais: {required: false},
DirNacimiento_CPProvincia: {required: false},
DirNacimiento_CPLocalidad: {required: false},
DirNacimiento_codpos: {required: false},
DirNacimiento_direccion: {required: false},
DirCenso_idpais: {required: false},
DirCenso_CPProvincia: {required: false},
DirCenso_CPLocalidad: {required: false},
DirCenso_codpos: {required: false},
DirCenso_direccion: {required: false}
},
messages: {
Nombre: {
required: "Es necesario asignar un Nombre",
maxlength:"La longitud máxima del Nombre es de 50 caracteres"
},
Apellido1: {
required: "Es necesario asignar Apellidos",
maxlength:"La longitud máxima de los Apellidos es de 50 caracteres"
},
Apellido2: {
required: "Es necesario asignar Apellidos",
maxlength:"La longitud máxima de los Apellidos es de 50 caracteres"
},
NIFCIFPASS: "Debe asignar un NIF, CIF o Pasaporte valido",
TipoNIFCIFPASS: "Debe asignar un NIF, CIF o Pasaporte valido",
NombreEmpresa: {
maxlength:"La longitud máxima de la empresa es de 150 caracteres"
},
FechaNacimiento:"Indique una fecha de nacimiento",
Telefonos:"Indique al menos 1 teléfono",
Email: {
required: "No ha asignado un email",
email: "El email no parece tener un formato válido",
},
Pass: {
required: "No ha asignado una contraseña",
maxlength:"La longitud máxima de la contraseña es de 30 caracteres y la mínima de 6"
},
DirNacimiento_idpais: "Seleccione un país de nacimiento",
DirNacimiento_CPProvincia: "Seleccione una provincia de nacimiento",
DirNacimiento_CPLocalidad: "Seleccione una localidad de nacimiento",
DirNacimiento_codpos: "Seleccione un código postal de nacimiento",
DirNacimiento_direccion: "Introduzca una direción de nacimiento",
DirCenso_idpais: "Seleccione un país de censo",
DirCenso_CPProvincia: "Seleccione una provincia de censo",
DirCenso_CPLocalidad: "Seleccione una localidad de censo",
DirCenso_codpos: "Seleccione un código postal de censo",
DirCenso_direccion: "Introduzca una direción de censo"
},
submitHandler: function(form) {
// Si todo ha ido OK al validar, guardo los datos del usuario en el servidor
that.GuardarMisDatos();
},
invalidHandler: function(event, validator) {
//Si la validación falla informo al usuario
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Hay un campo incorrecto.'
: 'Hay errores en ' + errors + ' campos.';
$('#FormMisDatos').find('div[id="Mensaje"]').html(message);
$('#FormMisDatos').find('div[id="Mensaje"]').show().removeClass('hidden');
} else {
$('#FormMisDatos').find('div[id="Mensaje"]').hide();
}
}
});
}, //PrepararFormulario
BorrarUsuario: function () {
var idusuario=this.idusuario;
bootbox.dialog({message: "¿Está seguro de que quiere borrar definitivamente su cuenta?",title: "Borrar Usuario",
buttons: {
success: {
label: "Borrar",
className: "btn-danger",
callback: function() {
$.ajax({
url: 'https://segovia.atencionciudadana.es/rest/data.php/borrarusuario/'+idusuario,
type: 'POST',
}).always(function( msg ) {
window.location.replace('https://segovia.atencionciudadana.es/inicio.php?cerrarsesion=si');
});
}
},
danger: {
label: "Cancelar",
className: "btn",
callback: function() {
//Example.show("uh oh, look out!");
}
}
}
});
}
});
var misDatosView = new MisDatosView();
//------------------------------------------------------------------------------
//CREDITOS----------------------------------------------------------------------
//VISTA historial de créditos
var HistorialCreditosView = Backbone.View.extend({
el: '#historico_creditos',
initialize : function(options) {
//Pongo el cargando
var template = _.template($('#Template-Loading').html(), {});
this.$el.html(template);
var that=this;
}, //initialize
render: function (options) {
this.idusuario=options.idusuario;
var that=this;
var O = $.getJSON("rest/data.php/listado_creditos/"+this.idusuario, function(historico_creditos) {
var total_creditos = 0;
$.each(historico_creditos, function(index, credito){
total_creditos += parseFloat(credito.creditos ? credito.creditos : 0);
switch (credito.tipoingreso) {
case 1:
credito.tipoingreso = '
Paypal | ';
break;
case 2:
credito.tipoingreso = '
Redsys | ';
break;
case 3:
credito.tipoingreso = '
por código en el registro | ';
break;
case 4:
credito.tipoingreso = '
movimiento de administrador | ';
break;
default:
credito.tipoingreso = "
Otros | ";
}
});
var template = _.template($('#Template-historico-creditos').html(), {historico_creditos: historico_creditos, total_creditos: total_creditos});
that.$el.html(template);
});
}, //render
});
var historialCreditosView = new HistorialCreditosView();
//-------------------------------------------------------------------------------
//CONTRATOS---------------------------------------------------------------------
//VISTA Listado de contratos
var ContratosListaView = Backbone.View.extend({
el: '#contenedor_contratos',
initialize : function() {
this.contratos = new Contratos();//Tiene que ser publica para que sea accesible desde backgridjs
this.incidents = new Incidents();
gridContratos = null;//privada
gridOpenIncidents= null;
}, //initialize
GuardarContrato: function () {
var contratoDetails = $('#FormEditarGrabarContrato').serializeObject();//currentTarget es el form, es el objetivo del evento
if (contratoDetails.ActivoResponds48h) {
if (contratoDetails.RespondTime == "")
contratoDetails.RespondTime = 48;
} else {
if (contratoDetails.RespondTime != "")
contratoDetails.RespondTime = "";
}
var contrato= new Contrato();
contrato.save(contratoDetails, {
success: function (contrato,response) {
$('#ModalEditarGrabarContrato').modal('hide');
CargaContratos();
inicioListaContratosView.changeProvincia();
},
error: function (contrato,response) {
$('#FormEditarGrabarContrato').find('div[id="Mensaje"]').html(response.responseText);
$('#FormEditarGrabarContrato').find('div[id="Mensaje"]').show().removeClass('hidden');
}
});
return false;
}, //GuardarAdministrador
PrepararFormulario: function () {
var that=this;
// Aquí cargo los requisitos y todo lo que lleve el formulario
//Validar el formulario
$("#FormEditarGrabarContrato").on('submit', function (e){
//Evito que mande el formulario
e.preventDefault();//En realidad no mando el formulario, serializo su contenido y lo mando con backbone/ajax
});
$("#FormEditarGrabarContrato").validate({
errorLabelContainer: "#FormEditarGrabarContrato_Mensaje",
wrapper: "li",
rules: {
Nombre: {
required:true,
maxlength:150
},
NombreMostrar: {
required:true,
maxlength:150
},
PagoMinimoMeses: {
required:true,
digits: true
},
PagoPrecioMes: {
required:true,
number: true
},
NIFCIFPASS: {
required:true,
maxlength:9
},
TipoNIFCIFPASS: {
required:true,
},
Logo: {
maxlength:250
},
Telefonos: {
required:true,
},
Email: {
required: true,
email: true,
maxlength:100
},
emailENV: {
required: true,
email: true,
maxlength:100
},
emailSMTPENV: {
required: true,
maxlength:100
},
emailUsuarioENV: {
required: true,
maxlength:100
},
emailPassENV: {
required: true,
maxlength:100
},
Dir_idpais: {required: true, min:1},
Dir_CPProvincia: {required: true, min:1},
Dir_CPLocalidad: {required: true, min:1},
Dir_codpos: {required: true, min:1},
Dir_direccion: {required: true}
},
messages: {
Nombre: {
required: "Es necesario asignar un Nombre",
maxlength:"La longitud máxima del Nombre es de 150 caracteres"
},
NombreMostrar: {
required: "Es necesario asignar un Nombre para mostrar a los usuarios",
maxlength:"La longitud máxima del Nombre a Mostrar es de 150 caracteres"
},
PagoMinimoMeses: {
digits: "Es necesario seleccionar un número mínimo de meses que puede pagar y debe ser un número entero",
required: "Es necesario seleccionar un número de meses para pago mínimo y debe ser un número entero",
},
PagoPrecioMes: {
number: "Es necesario seleccionar un precio por 1 mes y debe ser un número",
required: "Es necesario seleccionar un precio por 1 mes y debe ser un número",
},
NIFCIFPASS:"Debe asignar un NIF, CIF o Pasaporte",
TipoNIFCIFPASS: "Debe asignar un tipo NIF, CIF o Pasaporte",
logo:"Indique una fecha de nacimiento",
Telefonos:"Indique al menos 1 teléfono",
Email: {
required: "No ha asignado un email",
email: "El email no parece tener un formato válido",
},
emailENV: {
required: "No ha asignado un email de envío",
email: "El email no parece tener un formato válido",
},
emailSMTPENV: {
required: "No ha asignado un servidor SMTP para el correo de envío",
},
emailUsuarioENV: {
required: "No ha asignado un usuario para el correo de envíos",
maxlength:"La longitud máxima del usuario del correo de envíos es de {0} caracteres"
},
emailPassENV: {
required: "No ha asignado una contraseña para el correo de envíos",
maxlength:"La longitud máxima de la contraseña del correo de envíos es de {0} caracteres"
},
Dir_idpais: "Seleccione un país",
Dir_CPProvincia: "Seleccione una provincia",
Dir_CPLocalidad: "Seleccione una localidad",
Dir_codpos: "Seleccione un código postal",
Dir_direccion: "Introduzca una direción"
},
submitHandler: function(form) {
// Si todo ha ido OK al validar, guardo los datos de configuracion en el servidor
that.GuardarContrato();
},
invalidHandler: function(event, validator) {
//Si la validación falla informo al usuario
var errors = validator.numberOfInvalids();
if (errors) {
var message = errors == 1
? 'Hay un campo incorrecto.'
: 'Hay errores en ' + errors + ' campos.';
$('#FormEditarGrabarContrato_Mensaje').html(message);
$('#FormEditarGrabarContrato_Mensaje').show().removeClass('hidden');
} else {
$('#FormEditarGrabarContrato_Mensaje').hide();
}
}
});
}, //PrepararFormulario
render: function () {
//Pongo el cargando
var template = _.template($('#Template-Loading').html(), {});
this.$el.html(template);
var that = this; //La función success es anónima, y this solo tiene sentido en este contexto no en los eventos async resultado
gridContratos = new Backgrid.Grid({
columns : [{
name: "idcontrato", // The key of the model attribute
label: "Nº", // The name to display in the header
editable: false, // By default every cell in a column is editable, but *ID* shouldn't be
// Defines a cell type, and ID is displayed as an integer without the ',' separating 1000s.
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
},{
name: "Nombre",
label: "Nombre",
// The cell type can be a reference of a Backgrid.Cell subclass, any Backgrid.Cell subclass instances like *id* above, or a string
cell: "string", // This is converted to "StringCell" and a corresponding class in the Backgrid package namespace is looked up
editable: false
},{
name: "NombreMostrar",
label: "Nombre Mostrar",
cell: "string",
editable: false
},{
name: "UsuarioTitular",
label: "Administrador", //gonzalo
cell: "string" ,
editable: false
},{
name: "FechaAlta",
label: "Alta",
cell: FechaCell,
editable: false
},{
name: "Telefonos",
label: "Teléfonos", //gonzalo
cell: "string",
editable: false
},{
name: "Email",
label: "Email pagos", //gonzalo
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue) {
return '
'+rawValue+'';
//You can use rawValue to custom your html, you can change this value using the name parameter.
}
}),
cell: "html", // Renders the value in an HTML anchor element
editable: false
},{
name: "Direccion",
label: "Direccion",
cell: "string",
editable: false
},{
name: "Activo",
label: "Activo",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue) {
if (rawValue==1)
return '
Sí';
return '
No';
//You can use rawValue to custom your html, you can change this value using the name parameter.
}
}),
cell: "html",
editable: false,
}, {
name: "ActivoResponds48h",
label: "Activo Incidencias (Responde 48H)",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue) {
if (rawValue == 1)
return '
Sí';
return '
No'
}
}),
cell: "html",
editable: false
}, {
name:"",
label:"",
cell: ButtonCellContratos
}
],
collection: that.contratos
}); //Fin inicializo grid
gridOpenIncidents = new Backgrid.Grid({
columns : [
{
name: "idincidencia",
label: "ID INCIDENCIA",
editable: false,
cell: Backgrid.IntegerCell.extend({
orderSeparator: ''
})
},
{
name: "idagent",
label: "AGENTE ID",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue) {
if (rawValue == "NO ASIGNADO")
return '
' + rawValue + ''
else
return '
' + rawValue + ''
}
}),
cell: "html",
editable: false,
},
{
name: "fechaincioincidente",
label: "FECHA INCIO INCIDENTE",
cell: timeCell,
editable: false,
},
{
name: "fechacierreincidencia",
label: "FECHA PREVISTA FIN",
cell: timeCell,
editable: false
},
{
name: "fechaagenteasignado",
label: "FECHA Y HORA DE AGENTE ASIGNADO",
cell: timeCell,
editable: false
},
{
name: "fechaprevistafin",
label: "FECHA CIERRE INCIDENCIA",
cell: timeCell,
editable: false
},
{
name: "textdelaincidencia",
label: "TEXTO DE LA INCIDENCIA",
cell: "string",
editable: false
},
{
name: "timezone",
label: "USER TIMEZONE",
cell: "string",
editable: false
},
{
name: "documentsenciados",
label: "DOCUMENTOS ENVIADOS POR EL USUARIO",
cell: ButtonCellFileDownload,
editable: false
},
{
name: "estado",
label: "ESTADO",
formatter: _.extend({}, Backgrid.CellFormatter.prototype, {
fromRaw: function (rawValue) {
if (rawValue == 0)
return '
Abierto';
else if (rawValue == 1)
return '
En Curso';
else if (rawValue == 2)
return '
Cerrado';
}
}),
cell: "html",
editable: false
},
{
name: "message",
label: "MENSAJE",
cell: "string",
editable: false
},
],
collection: that.incidents
});
// Renderizo el grid y lo muestro como html en el documento
$("#grid-contratos").html(gridContratos.render().el);
$("#grid-openIncidents").html(gridOpenIncidents.render().el);
that.contratos.fetch({
reset: true,
success: function (contratos) {
$("#labelNumContratos").html('Nº de contratos:
'+contratos.length+'');//gonzalo
},
error: function (contratos, response) {
$("#labelNumContratos").html('Nº de contratos: -');//gonzalo
var errortext=response.responseText;
if (errortext.length<=0)
errortext='error: No se ha recibido nada';
var template = _.template($('#Template-Error').html(), {error : errortext});
that.$el.html(template);
}
});
that.incidents.fetch({
reset: true,
success: function (incidents) {
console.log('success');
},
error: function(incidents, response) {
console.log('error');
}
})
}, //render
CreaNuevoContrato: function () {
$('#ModalEditarGrabarContratoTitle').html('Crear nuevo contrato');
var template = _.template($('#Template-Editar-Grabar-Contrato').html(), {contrato : null});
$('#ModalEditarGrabarContratoMensaje').html(template);
contratosListaView.PrepararFormulario();
$('#ModalEditarGrabarContrato').modal('show');
}, //CreaNuevoContrato
});
var contratosListaView = new ContratosListaView()