Cambio a ES6 a ubigeo

parent d9d4acc7
# Documentación <img src="http://sacooliveros.edu.pe/images/sacooliveros/Home/logos/logo-saco-apeiron.png" align="center" />
- [Documentación](#documentación) # Proyecto Estandar
- [Servlets](#servlets)
- [Respuestas](#respuestas)
## JSP ## Introducción
## Beans Este proyecto recopila los estándares que se utilizan en los proyectos con la finalidad de ayudar a entenderlos de una manera práctica.
## Servlets
## Documentación
- [Estructura de proyecto]()
- [Servlets](#servlets)
- [Respuestas](#respuestas)
### Servlets
- Respuestas - Respuestas
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demojsoncrud.beans; package demojsoncrud.beans;
import java.io.Serializable; import java.io.Serializable;
/**
*
* @author Alonso
*/
public class UbigeoBean implements Serializable { public class UbigeoBean implements Serializable {
private String codigoDepartamento; private String codigoDepartamento;
......
...@@ -5,17 +5,11 @@ import org.json.JSONObject; ...@@ -5,17 +5,11 @@ import org.json.JSONObject;
public interface PersonaDAO { public interface PersonaDAO {
public JSONObject listarPersonaTest();
public JSONObject listarPersona(String search, String draw, String start, String length); public JSONObject listarPersona(String search, String draw, String start, String length);
public JSONObject registrarPersona(JSONObject datos); public JSONObject registrarPersona(JSONObject datos);
public JSONObject editarPersona(JSONObject datos); public JSONObject editarPersona(JSONObject datos);
public JSONObject activarPersona(PersonaBean bean);
public JSONObject desactivarPersona(PersonaBean bean);
public JSONObject cambiarEstado(JSONObject datos); public JSONObject cambiarEstado(JSONObject datos);
......
...@@ -16,8 +16,8 @@ public interface UbigeoDAO { ...@@ -16,8 +16,8 @@ public interface UbigeoDAO {
public JSONObject listarDepartamento(); public JSONObject listarDepartamento();
public JSONObject listarProvincia(UbigeoBean bean); public JSONObject listarProvincia(JSONObject datos);
public JSONObject listarDistrito(UbigeoBean bean); public JSONObject listarDistrito(JSONObject datos);
} }
...@@ -10,16 +10,6 @@ public class PersonaService { ...@@ -10,16 +10,6 @@ public class PersonaService {
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER); DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
PersonaDAO service = daoFactory.getPersonaDAO(); PersonaDAO service = daoFactory.getPersonaDAO();
public JSONObject listarPersonaTest() {
JSONObject jsonReturn = null;
try {
jsonReturn = service.listarPersonaTest();
} catch (Exception e) {
e.getMessage();
}
return jsonReturn;
}
public JSONObject listarPersona(String search, String draw, String start, String length) { public JSONObject listarPersona(String search, String draw, String start, String length) {
JSONObject jsonReturn = null; JSONObject jsonReturn = null;
try { try {
...@@ -49,24 +39,6 @@ public class PersonaService { ...@@ -49,24 +39,6 @@ public class PersonaService {
} }
return jsonReturn; return jsonReturn;
} }
public JSONObject activarPersona(PersonaBean bean) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.activarPersona(bean);
} catch (Exception e) {
}
return jsonReturn;
}
public JSONObject desactivarPersona(PersonaBean bean) {
JSONObject jsonReturn = null;
try {
jsonReturn = service.desactivarPersona(bean);
} catch (Exception e) {
}
return jsonReturn;
}
public JSONObject cambiarEstado(JSONObject datos) { public JSONObject cambiarEstado(JSONObject datos) {
JSONObject respuesta = null; JSONObject respuesta = null;
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demojsoncrud.services; package demojsoncrud.services;
import demojsoncrud.beans.UbigeoBean; import demojsoncrud.beans.UbigeoBean;
...@@ -10,10 +5,6 @@ import demojsoncrud.dao.DAOFactory; ...@@ -10,10 +5,6 @@ import demojsoncrud.dao.DAOFactory;
import demojsoncrud.dao.UbigeoDAO; import demojsoncrud.dao.UbigeoDAO;
import org.json.JSONObject; import org.json.JSONObject;
/**
*
* @author Alonso
*/
public class UbigeoService { public class UbigeoService {
DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER); DAOFactory daoFactory = DAOFactory.getDAOFactory(DAOFactory.SQL_SERVER);
...@@ -28,19 +19,19 @@ public class UbigeoService { ...@@ -28,19 +19,19 @@ public class UbigeoService {
return jsonReturn; return jsonReturn;
} }
public JSONObject listarProvincia(UbigeoBean bean) { public JSONObject listarProvincia(JSONObject datos) {
JSONObject jsonReturn = null; JSONObject jsonReturn = null;
try { try {
jsonReturn = service.listarProvincia(bean); jsonReturn = service.listarProvincia(datos);
} catch (Exception e) { } catch (Exception e) {
} }
return jsonReturn; return jsonReturn;
} }
public JSONObject listarDistrito(UbigeoBean bean) { public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = null; JSONObject jsonReturn = null;
try { try {
jsonReturn = service.listarDistrito(bean); jsonReturn = service.listarDistrito(datos);
} catch (Exception e) { } catch (Exception e) {
} }
return jsonReturn; return jsonReturn;
......
package demojsoncrud.servlets; package demojsoncrud.servlets;
import demojsoncrud.beans.PersonaBean;
import demojsoncrud.services.PersonaService; import demojsoncrud.services.PersonaService;
import static demojsoncrud.utilities.CustomHttpServletRequest.getBodyJsonObject; import static demojsoncrud.utilities.CustomHttpServletRequest.getBodyJsonObject;
import java.io.IOException; import java.io.IOException;
...@@ -16,31 +15,32 @@ public class PersonaServlet extends HttpServlet { ...@@ -16,31 +15,32 @@ public class PersonaServlet extends HttpServlet {
@Override @Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion"); String param = request.getParameter("accion");
if ("listarPersonaTest".equals(param)) { switch (param) {
listarPersonaTest(request, response); case "listarPersona":
} else if ("listarPersona".equals(param)) { listarPersona(request, response);
listarPersona(request, response); break;
} else if ("registrarPersona".equals(param)) { case "registrarPersona":
registrarPersona(request, response); registrarPersona(request, response);
} else if ("editarPersona".equals(param)) { break;
editarPersona(request, response); case "editarPersona":
} else if ("activarPersona".equals(param)) { editarPersona(request, response);
activarPersona(request, response); break;
} else if ("desactivarPersona".equals(param)) { case "cambiarEstado":
desactivarPersona(request, response); cambiarEstado(request, response);
} else if ("cambiarEstado".equals(param)) { break;
cambiarEstado(request, response); default:
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
JSONObject respuesta = new JSONObject();
respuesta
.put("status", false)
.put("message", "No existe la url solicitada.")
.put("data", "");
pw.print(respuesta);
break;
} }
} }
private void listarPersonaTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PrintWriter pw = response.getWriter();
PersonaService service = new PersonaService();
JSONObject json = service.listarPersonaTest();
pw.print(json);
}
private void listarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException { private void listarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json"); response.setContentType("application/json");
PrintWriter pw = response.getWriter(); PrintWriter pw = response.getWriter();
...@@ -76,40 +76,6 @@ public class PersonaServlet extends HttpServlet { ...@@ -76,40 +76,6 @@ public class PersonaServlet extends HttpServlet {
pw.print(respuesta); pw.print(respuesta);
} }
private void activarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PersonaService service = new PersonaService();
PrintWriter pw = response.getWriter();
String json = request.getParameter("json");
JSONObject jsonObject = new JSONObject(json);
String codigo = jsonObject.getString("codigo");
PersonaBean bean = new PersonaBean();
bean.setCodigo(codigo);
JSONObject jsonReturn = service.activarPersona(bean);
pw.print(jsonReturn);
}
private void desactivarPersona(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json");
PersonaService service = new PersonaService();
PrintWriter pw = response.getWriter();
String json = request.getParameter("json");
JSONObject jsonObject = new JSONObject(json);
String codigo = jsonObject.getString("codigo");
PersonaBean bean = new PersonaBean();
bean.setCodigo(codigo);
JSONObject jsonReturn = service.desactivarPersona(bean);
pw.print(jsonReturn);
}
private void cambiarEstado(HttpServletRequest request, HttpServletResponse response) throws IOException { private void cambiarEstado(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json"); response.setContentType("application/json");
PrintWriter pw = response.getWriter(); PrintWriter pw = response.getWriter();
......
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package demojsoncrud.servlets; package demojsoncrud.servlets;
import demojsoncrud.beans.UbigeoBean; import demojsoncrud.beans.UbigeoBean;
import demojsoncrud.services.UbigeoService; import demojsoncrud.services.UbigeoService;
import static demojsoncrud.utilities.CustomHttpServletRequest.getBodyJsonObject;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.ServletException;
...@@ -15,16 +11,12 @@ import javax.servlet.http.HttpServletRequest; ...@@ -15,16 +11,12 @@ import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject; import org.json.JSONObject;
/**
*
* @author Alonso
*/
public class UbigeoServlet extends HttpServlet { public class UbigeoServlet extends HttpServlet {
@Override @Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("accion"); String param = request.getParameter("accion");
response.setCharacterEncoding("UTF-8");
if ("listarDepartamento".equals(param)) { if ("listarDepartamento".equals(param)) {
listarDepartamento(request, response); listarDepartamento(request, response);
} else if ("listarProvincia".equals(param)) { } else if ("listarProvincia".equals(param)) {
...@@ -46,36 +38,20 @@ public class UbigeoServlet extends HttpServlet { ...@@ -46,36 +38,20 @@ public class UbigeoServlet extends HttpServlet {
response.setContentType("application/json"); response.setContentType("application/json");
PrintWriter pw = response.getWriter(); PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService(); UbigeoService service = new UbigeoService();
JSONObject datos = new JSONObject();
String json = request.getParameter("json"); datos = getBodyJsonObject(request);
JSONObject jsonObject = new JSONObject(json); JSONObject respuesta = service.listarProvincia(datos.getJSONObject("json"));
pw.print(respuesta);
String codigoDepartamento = jsonObject.getString("codigoDepartamento");
UbigeoBean bean = new UbigeoBean();
bean.setCodigoDepartamento(codigoDepartamento);
JSONObject jsonReturn = service.listarProvincia(bean);
pw.print(jsonReturn);
} }
private void listarDistrito(HttpServletRequest request, HttpServletResponse response) throws IOException { private void listarDistrito(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("application/json"); response.setContentType("application/json");
PrintWriter pw = response.getWriter(); PrintWriter pw = response.getWriter();
UbigeoService service = new UbigeoService(); UbigeoService service = new UbigeoService();
JSONObject datos = new JSONObject();
String json = request.getParameter("json"); datos = getBodyJsonObject(request);
JSONObject jsonObject = new JSONObject(json); JSONObject respuesta = service.listarDistrito(datos.getJSONObject("json"));
pw.print(respuesta);
String codigoDepartamento = jsonObject.getString("codigoDepartamento");
String codigoProvincia = jsonObject.getString("codigoProvincia");
UbigeoBean bean = new UbigeoBean();
bean.setCodigoDepartamento(codigoDepartamento);
bean.setCodigoProvincia(codigoProvincia);
JSONObject jsonReturn = service.listarDistrito(bean);
pw.print(jsonReturn);
} }
} }
...@@ -14,80 +14,6 @@ import org.json.JSONObject; ...@@ -14,80 +14,6 @@ import org.json.JSONObject;
public class PersonaSqlserverDAO implements PersonaDAO { public class PersonaSqlserverDAO implements PersonaDAO {
@Override @Override
public JSONObject listarPersonaTest() {
JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray();
ResponseHelper response = new ResponseHelper();
PreparedStatement psListarPersona = null;
ResultSet rsListarPersona = null;
Connection connection = null;
String base = "demojsoncrud";
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "select "
+ "a.codigo, "
+ "a.dni, "
+ "a.apellidos, "
+ "a.nombres, "
+ "a.edad, "
+ "a.correo, "
+ "a.estado "
+ "from persona a ";
psListarPersona = connection.prepareStatement(sql);
rsListarPersona = psListarPersona.executeQuery();
while (rsListarPersona.next()) {
PersonaBean personaBean = new PersonaBean();
int q = 1; //Contador para las columnas
personaBean.setCodigo(rsListarPersona.getString(q++));
personaBean.setDni(rsListarPersona.getString(q++));
personaBean.setApellidos(rsListarPersona.getString(q++));
personaBean.setNombres(rsListarPersona.getString(q++));
personaBean.setEdad(rsListarPersona.getString(q++));
personaBean.setCorreo(rsListarPersona.getString(q++));
personaBean.setEstado(rsListarPersona.getString(q++));
JSONObject obj = new JSONObject(personaBean);
data.put(obj);
}
JSONObject jsonData = new JSONObject();
jsonData.put("personas", data);
response.setData(jsonData);
response.setMessage("Listado correcto!");
response.setStatus(true);
} catch (SQLException e) {
response.setMessage("Error -> " + e.getMessage() + " [" + e.getErrorCode() + "]");
response.setStatus(false);
} finally {
try {
if (rsListarPersona != null) {
rsListarPersona.close();
}
if (psListarPersona != null) {
psListarPersona.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
response.setMessage("Error -> " + e.getMessage() + " [" + e.getErrorCode() + "]");
response.setStatus(false);
}
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject listarPersona(String search, String draw, String start, String length) { public JSONObject listarPersona(String search, String draw, String start, String length) {
JSONObject jsonReturn = new JSONObject(); JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray(); JSONArray data = new JSONArray();
...@@ -303,106 +229,6 @@ public class PersonaSqlserverDAO implements PersonaDAO { ...@@ -303,106 +229,6 @@ public class PersonaSqlserverDAO implements PersonaDAO {
} }
@Override @Override
public JSONObject activarPersona(PersonaBean bean) {
JSONObject jsonReturn = new JSONObject();
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
int resultPersona = 0;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "update persona "
+ "set estado = 1 "
+ "where codigo = ?";
psEditarPersona = connection.prepareStatement(sql);
psEditarPersona.setString(1, bean.getCodigo());
resultPersona = psEditarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Se actualizo correctamente");
response.setStatus(true); // ACTUALIZO
} else {
response.setMessage("Error al actualizar");
response.setStatus(false); // ERROR
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (connection != null) {
connection.close();
}
if (psEditarPersona != null) {
psEditarPersona.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
}
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject desactivarPersona(PersonaBean bean) {
JSONObject jsonReturn = new JSONObject();
String base = "demojsoncrud";
Connection connection = null;
PreparedStatement psEditarPersona = null;
int resultPersona = 0;
ResponseHelper response = new ResponseHelper();
try {
connection = SqlserverDAOFactory.obtenerConexion(base);
String sql
= "update persona "
+ "set estado = 0 "
+ "where codigo = ?";
psEditarPersona = connection.prepareStatement(sql);
psEditarPersona.setString(1, bean.getCodigo());
resultPersona = psEditarPersona.executeUpdate();
if (resultPersona == 1) {
response.setMessage("Se actualizo correctamente");
response.setStatus(true); // ACTUALIZO
} else {
response.setMessage("Error al actualizar");
response.setStatus(false); // ERROR
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
} finally {
try {
if (connection != null) {
connection.close();
}
if (psEditarPersona != null) {
psEditarPersona.close();
}
} catch (SQLException e) {
response.setStatus(false);
response.setMessage("Error al actualizar -> " + e.getMessage() + "[" + e.getErrorCode() + "]");
}
}
jsonReturn = new JSONObject(response);
return jsonReturn;
}
@Override
public JSONObject cambiarEstado(JSONObject datos) { public JSONObject cambiarEstado(JSONObject datos) {
System.out.println(datos); System.out.println(datos);
JSONObject jsonReturn = new JSONObject(); JSONObject jsonReturn = new JSONObject();
......
...@@ -34,12 +34,12 @@ public class UbigeoSqlserverDAO implements UbigeoDAO { ...@@ -34,12 +34,12 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
try { try {
connection = SqlserverDAOFactory.obtenerConexion(base); connection = SqlserverDAOFactory.obtenerConexion(base);
String sql String sql
= "select " = "select "
+ "codDepartamento as codigoDepartamento, " + "codDepartamento as codigoDepartamento, "
+ "nombreDepartamento as nombreDepartamento " + "nombreDepartamento as nombreDepartamento "
+ "from ubigeo " + "from ubigeo "
+ "group by codDepartamento, nombreDepartamento " + "group by codDepartamento, nombreDepartamento "
+ "order by nombreDepartamento"; + "order by nombreDepartamento";
psListarDepartamento = connection.prepareStatement(sql); psListarDepartamento = connection.prepareStatement(sql);
rsListarDepartamento = psListarDepartamento.executeQuery(); rsListarDepartamento = psListarDepartamento.executeQuery();
while (rsListarDepartamento.next()) { while (rsListarDepartamento.next()) {
...@@ -84,7 +84,8 @@ public class UbigeoSqlserverDAO implements UbigeoDAO { ...@@ -84,7 +84,8 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
} }
@Override @Override
public JSONObject listarProvincia(UbigeoBean bean) { public JSONObject listarProvincia(JSONObject datos) {
System.out.println(datos);
JSONObject jsonReturn = new JSONObject(); JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray(); JSONArray data = new JSONArray();
PreparedStatement psListarProvincia = null; PreparedStatement psListarProvincia = null;
...@@ -96,15 +97,15 @@ public class UbigeoSqlserverDAO implements UbigeoDAO { ...@@ -96,15 +97,15 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
try { try {
connection = SqlserverDAOFactory.obtenerConexion(base); connection = SqlserverDAOFactory.obtenerConexion(base);
String sql String sql
= "select " = "select "
+ "codProvincia as codigoProvincia, " + "codProvincia as codigoProvincia, "
+ "nombreProvincia as nombreProvincia " + "nombreProvincia as nombreProvincia "
+ "from ubigeo " + "from ubigeo "
+ "where codDepartamento = ? " + "where codDepartamento = ? "
+ "group by codProvincia, nombreProvincia " + "group by codProvincia, nombreProvincia "
+ "order by nombreProvincia"; + "order by nombreProvincia";
psListarProvincia = connection.prepareStatement(sql); psListarProvincia = connection.prepareStatement(sql);
psListarProvincia.setString(1, bean.getCodigoDepartamento()); psListarProvincia.setInt(1, datos.getInt("codigoDepartamento"));
rsListarProvincia = psListarProvincia.executeQuery(); rsListarProvincia = psListarProvincia.executeQuery();
while (rsListarProvincia.next()) { while (rsListarProvincia.next()) {
UbigeoBean ubigeoBean = new UbigeoBean(); UbigeoBean ubigeoBean = new UbigeoBean();
...@@ -148,7 +149,7 @@ public class UbigeoSqlserverDAO implements UbigeoDAO { ...@@ -148,7 +149,7 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
} }
@Override @Override
public JSONObject listarDistrito(UbigeoBean bean) { public JSONObject listarDistrito(JSONObject datos) {
JSONObject jsonReturn = new JSONObject(); JSONObject jsonReturn = new JSONObject();
JSONArray data = new JSONArray(); JSONArray data = new JSONArray();
PreparedStatement psListarDistrito = null; PreparedStatement psListarDistrito = null;
...@@ -160,15 +161,15 @@ public class UbigeoSqlserverDAO implements UbigeoDAO { ...@@ -160,15 +161,15 @@ public class UbigeoSqlserverDAO implements UbigeoDAO {
try { try {
connection = SqlserverDAOFactory.obtenerConexion(base); connection = SqlserverDAOFactory.obtenerConexion(base);
String sql String sql
= "select " = "select "
+ "codDistrito as codigoDistrito, " + "codDistrito as codigoDistrito, "
+ "nombreDistrito as nombreDistrito " + "nombreDistrito as nombreDistrito "
+ "from ubigeo " + "from ubigeo "
+ "where codProvincia = ? and codDepartamento = ? " + "where codProvincia = ? and codDepartamento = ? "
+ "order by nombreDistrito"; + "order by nombreDistrito";
psListarDistrito = connection.prepareStatement(sql); psListarDistrito = connection.prepareStatement(sql);
psListarDistrito.setString(1, bean.getCodigoProvincia()); psListarDistrito.setInt(1, datos.getInt("codigoProvincia"));
psListarDistrito.setString(2, bean.getCodigoDepartamento()); psListarDistrito.setInt(2, datos.getInt("codigoDepartamento"));
rsListarDistrito = psListarDistrito.executeQuery(); rsListarDistrito = psListarDistrito.executeQuery();
while (rsListarDistrito.next()) { while (rsListarDistrito.next()) {
UbigeoBean ubigeoBean = new UbigeoBean(); UbigeoBean ubigeoBean = new UbigeoBean();
......
...@@ -35,6 +35,22 @@ let fetchSo = (url, object) => { ...@@ -35,6 +35,22 @@ let fetchSo = (url, object) => {
) )
} }
/**
* Crea los elementos option del array que se pase como parametro
* @method createSelectOptions
* @param {JSONArray} obj array de objetos
* @param {String} valueName la key del json que se usará como value del elemento option
* @param {String} textName la key del json que se usará como text del elemento option
* @returns {Promise} Promise retorna status, msg
*/
let createSelectOptions = (obj, valueName, textName) => {
let options = ''
obj.forEach((data) => {
options += `<option value="${data[valueName]}">${data[textName]}</option>`
})
return options
}
let customSwal = { let customSwal = {
alert (title, text, type) { alert (title, text, type) {
let colors = { let colors = {
......
...@@ -70,10 +70,7 @@ let persona = { ...@@ -70,10 +70,7 @@ let persona = {
url: '../PersonaServlet?accion=listarPersona', url: '../PersonaServlet?accion=listarPersona',
type: 'POST', type: 'POST',
dataType: 'json', dataType: 'json',
data: {search: txtCriterioBusqueda}, data: {search: txtCriterioBusqueda}
/*success: function (data) {
resolve(data)
}*/
}, },
columnDefs: [ columnDefs: [
{targets: 0, orderable: false, width: '5%', className: 'centrado'}, {targets: 0, orderable: false, width: '5%', className: 'centrado'},
...@@ -194,8 +191,7 @@ let limpiarCajasTexto = () => { ...@@ -194,8 +191,7 @@ let limpiarCajasTexto = () => {
$('#btn_agregar_persona').on('click', function () { $('#btn_agregar_persona').on('click', function () {
$('#txt_numero_documento').attr({ $('#txt_numero_documento').attr({
autofocus: true autofocus: true
}) }).val('')
$('#txt_numero_documento').val('')
$('#txt_apellidos').val('') $('#txt_apellidos').val('')
$('#txt_nombres').val('') $('#txt_nombres').val('')
$('#txt_edad').val('') $('#txt_edad').val('')
...@@ -233,7 +229,7 @@ let asignarEventos = () => { ...@@ -233,7 +229,7 @@ let asignarEventos = () => {
}) })
$('#tbl-persona tbody').on('click', '.editarPersona', (event) => { $('#tbl-persona tbody').on('click', '.editarPersona', (event) => {
let rowData = $('#tbl-persona').DataTable().row($(event.currentTarget).parents('tr')).data() let rowData = obtenerDatosTabla($(event.currentTarget).parents('tr'))
$('#txt_numero_documento_editar').val(rowData.dni) $('#txt_numero_documento_editar').val(rowData.dni)
$('#txt_apellidos_editar').val(rowData.apellidos) $('#txt_apellidos_editar').val(rowData.apellidos)
$('#txt_nombres_editar').val(rowData.nombres) $('#txt_nombres_editar').val(rowData.nombres)
...@@ -286,7 +282,7 @@ let asignarEventos = () => { ...@@ -286,7 +282,7 @@ let asignarEventos = () => {
.registrar() .registrar()
.then((data) => { .then((data) => {
customSwal customSwal
.alert('¡Exito!', 'Se registró con exito.', 'success') .alert('¡Exito!', data.message, 'success')
.then(() => { .then(() => {
$('#modal_registrar_persona').modal('hide') $('#modal_registrar_persona').modal('hide')
}) })
...@@ -295,7 +291,7 @@ let asignarEventos = () => { ...@@ -295,7 +291,7 @@ let asignarEventos = () => {
}) })
}) })
.catch((data) => { .catch((data) => {
customSwal.alert('¡Error!', 'No se registró con exito.', 'error') customSwal.alert('¡Error!', data.message, 'error')
}) })
} }
}) })
...@@ -337,7 +333,7 @@ let asignarEventos = () => { ...@@ -337,7 +333,7 @@ let asignarEventos = () => {
.editar() .editar()
.then((data) => { .then((data) => {
customSwal customSwal
.alert('¡Exito!', 'Se actualizó con exito.', 'success') .alert('¡Exito!', data.message, 'success')
.then(() => { .then(() => {
$('#modal_editar_persona').modal('hide') $('#modal_editar_persona').modal('hide')
}) })
...@@ -346,7 +342,7 @@ let asignarEventos = () => { ...@@ -346,7 +342,7 @@ let asignarEventos = () => {
}) })
}) })
.catch((data) => { .catch((data) => {
customSwal.alert('¡Error!', 'No se actualizó con exito.', 'error') customSwal.alert('¡Error!', data.message, 'error')
}) })
} }
}) })
...@@ -354,6 +350,7 @@ let asignarEventos = () => { ...@@ -354,6 +350,7 @@ let asignarEventos = () => {
$('#btn_buscar_criterio').on('click', function () { $('#btn_buscar_criterio').on('click', function () {
persona.listar() persona.listar()
}) })
$('#txt-busqueda').keyup(function (e) { $('#txt-busqueda').keyup(function (e) {
if (e.keyCode === 13) { if (e.keyCode === 13) {
persona.listar() persona.listar()
......
/* let ubigeo = {
* To change this license header, choose License Headers in Project Properties. consultarDepartamento () {
* To change this template file, choose Tools | Templates return new Promise((resolve, reject) => {
* and open the template in the editor. fetchSo('../UbigeoServlet?accion=listarDepartamento')
*/ .then((data) => {
resolve(data)
})
$(document).ready(function () { .catch((data) => {
reject(data)
init(); })
validarSelect(); })
},
}); consultarProvincia (codigoDepartamento) {
let json = {
function init() { codigoDepartamento: codigoDepartamento
listarDepartamento();
listarProvincia();
listarDistrito();
}
function listarDepartamento() {
$.ajax({
type: 'POST',
url: '../UbigeoServlet?accion=listarDepartamento',
beforeSend: function (xhr) {
},
success: function (data, textStatus, jqXHR) {
var status = data.status;
var departamentos = data.data.departamentos;
if (status) {
var select_departamento = '<option value="0">[ SELECCIONE ]</option>';
for (var i in departamentos) {
select_departamento += '<option value="' + departamentos[i].codigoDepartamento + '">' + departamentos[i].nombreDepartamento + '</option>';
}
$('#select_departamento').html(select_departamento);
$('#select_departamento').selectpicker('refresh');
} else {
}
},
complete: function (jqXHR, textStatus) {
} }
}); return new Promise((resolve, reject) => {
} fetchSo('../UbigeoServlet?accion=listarProvincia', json)
.then((data) => {
function listarProvincia() { resolve(data)
$('#select_departamento').on('change', function () { })
.catch((data) => {
var json = { reject(data)
codigoDepartamento: $('#select_departamento').val() })
}; })
},
$.ajax({ consultarDistrito (codigoDepartamento, codigoProvincia) {
type: 'POST', let json = {
url: '../UbigeoServlet?accion=listarProvincia', codigoProvincia: codigoProvincia,
dataType: 'json', codigoDepartamento: codigoDepartamento
data: {json: JSON.stringify(json)}, }
beforeSend: function (xhr) { return new Promise((resolve, reject) => {
fetchSo('../UbigeoServlet?accion=listarDistrito', json)
}, .then((data) => {
success: function (data, textStatus, jqXHR) { resolve(data)
var status = data.status; })
var provincias = data.data.provincias; .catch((data) => {
if (status) { reject(data)
var select_provincia = '<option value="0">[ SELECCIONE ]</option>'; })
for (var i in provincias) { })
select_provincia += '<option value="' + provincias[i].codigoProvincia + '">' + provincias[i].nombreProvincia + '</option>'; }
}
$('#select_provincia').html(select_provincia);
$('#select_provincia').selectpicker('refresh');
} else {
}
},
complete: function (jqXHR, textStatus) {
}
});
});
}
function listarDistrito() {
$('#select_provincia').on('change', function () {
var json = {
codigoDepartamento: $('#select_departamento').val(),
codigoProvincia: $('#select_provincia').val()
};
$.ajax({
type: 'POST',
url: '../UbigeoServlet?accion=listarDistrito',
dataType: 'json',
data: {json: JSON.stringify(json)},
beforeSend: function (xhr) {
},
success: function (data, textStatus, jqXHR) {
var status = data.status;
var distritos = data.data.distritos;
if (status) {
var select_distrito = '<option value="0">[ SELECCIONE ]</option>';
for (var i in distritos) {
select_distrito += '<option value="' + distritos[i].codigoDistrito + '">' + distritos[i].nombreDistrito + '</option>';
}
$('#select_distrito').html(select_distrito);
$('#select_distrito').selectpicker('refresh');
} else {
}
},
complete: function (jqXHR, textStatus) {
}
});
});
} }
function validarSelect() { let asignarEventos = () => {
let slDepartamento = document.querySelector('#select_departamento')
$('#select_departamento').on('change', function () { let slProvincia = document.querySelector('#select_provincia')
var select_departamento = $('#select_departamento').val(); let slDistrito = document.querySelector('#select_distrito')
if (select_departamento === '0') { slDepartamento.addEventListener('change', (e) => {
$('#select_provincia').html('<option value="0">[ SELECCIONE ]</option>'); let codigoDepartamento = parseInt(e.target.value)
$('#select_distrito').html('<option value="0">[ SELECCIONE ]</option>'); ubigeo.consultarProvincia(codigoDepartamento)
.then((data) => {
$('#select_provincia').selectpicker('refresh'); let opt = '<option value="0">[ SELECCIONE ]</option>'
$('#select_distrito').selectpicker('refresh'); opt += createSelectOptions(data.data.provincias, 'codigoProvincia', 'nombreProvincia')
slProvincia.innerHTML = opt
})
.then(() => {
$('#select_provincia').selectpicker('refresh')
})
})
slProvincia.addEventListener('change', (e) => {
let codigoDepartamento = parseInt(slDepartamento.value)
let codigoProvincia = parseInt(e.target.value)
ubigeo.consultarDistrito(codigoDepartamento, codigoProvincia)
.then((data) => {
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.distritos, 'codigoDistrito', 'nombreDistrito')
slDistrito.innerHTML = opt
})
.then(() => {
$('#select_distrito').selectpicker('refresh')
})
})
slDepartamento.addEventListener('change', (e) => {
let departamento = parseInt(e.target.value)
if (departamento === 0) {
slProvincia.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
slDistrito.innerHTML = '<option value="0">[ SELECCIONE ]</option>'
} else { } else {
$('#select_provincia').val(0); slProvincia.value = 0
$('#select_distrito').val(0); slDistrito.value = 0
$('#select_distrito').html('<option value="0">[ SELECCIONE ]</option>');
$('#select_provincia').selectpicker('refresh');
$('#select_distrito').selectpicker('refresh');
} }
}); $('#select_provincia').selectpicker('refresh')
$('#select_distrito').selectpicker('refresh')
})
}
} ubigeo
\ No newline at end of file .consultarDepartamento()
.then((data) => {
let element = document.querySelector('#select_departamento')
let opt = '<option value="0">[ SELECCIONE ]</option>'
opt += createSelectOptions(data.data.departamentos, 'codigoDepartamento', 'nombreDepartamento')
element.innerHTML = opt
})
.then(() => {
$('#select_departamento').selectpicker('refresh')
})
asignarEventos()
\ No newline at end of file
<%-- <%--
Document : index Document : index
Created on : 05-ene-2018, 20:49:32 Created on : 05-ene-2018, 20:49:32
Author : Alonso Author : Alonso
...@@ -31,7 +31,7 @@ ...@@ -31,7 +31,7 @@
<div class="col-md-4"> <div class="col-md-4">
<div class="form-group"> <div class="form-group">
<label class="text-uppercase">departamento<span class="text-danger"> (*)</span></label> <label class="text-uppercase">departamento<span class="text-danger"> (*)</span></label>
<select id="select_departamento" class="bootstrap-select" data-width="100%"> <select id="select_departamento" class="form-control" data-width="100%">
<option value="0">[ SELECCIONE ]</option> <option value="0">[ SELECCIONE ]</option>
</select> </select>
</div> </div>
...@@ -74,7 +74,7 @@ ...@@ -74,7 +74,7 @@
<script type="text/javascript" src="../plantilla/assets/js/pages/form_bootstrap_select.js"></script> <script type="text/javascript" src="../plantilla/assets/js/pages/form_bootstrap_select.js"></script>
<!--js--> <!--js-->
<script src="../js/general.js" type="text/javascript"></script>
<script src="../js/pages/ubigeo.js" type="text/javascript"></script> <script src="../js/pages/ubigeo.js" type="text/javascript"></script>
</body> </body>
</html> </html>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment