Files
2025-06-09 13:37:06 +02:00

1423 lines
55 KiB
Java

/**
* @(#) GestorMedicos.java
*/
package com.tarisan.servlets;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.tarisan.control.*;
import com.tarisan.data.*;
import com.tarisan.log.*;
import com.tarisan.util.DES;
import com.tarisan.util.Print;
import com.tarisan.util.Utilidades;
import com.tarisan.excepcion.ExcepcionTarisan;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.Vector;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
/**
* Servlet direccionador a páginas JSP para el módulo de gestión de médicos.
* @author <a href="mailto:sistemas@imqnavarra.com">Dpto. Informática</a>.
* @version 1.0, 24/09/2003
*/
public class GestorMedicos extends HttpServlet implements Constantes
{
/**
* Recepción de la petición de acceso al módulo de gestión de médicos solicitada por el cliente.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que recibirá el cliente.
* @throws
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LogTarisan.logger.log(NivelLog.INFO, "GestorMedicos.service().INI");
response.setHeader("Expires", "0");
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
HttpSession sesion = request.getSession(true);
if(sesion.isNew() || (sesion.getAttribute("USUARIO") == null))
{
LogTarisan.logger.log(NivelLog.DEBUG, "Sesión no iniciada");
response.sendRedirect("../html/login.html");
}
else
{
if (sesion.getAttribute("PACIENTE") != null)
{
sesion.removeAttribute("PACIENTE");
}
LogTarisan.logger.log(NivelLog.DEBUG, "Entrada aceptada al módulo de Gestión de Médicos");
String opcion = request.getParameter("OPCION");
this.evaluarOpcion(opcion, request, response, sesion);
}
LogTarisan.logger.log(NivelLog.INFO, "GestorMedicos.service().FIN");
}
/**
* Evalúa la opción del módulo de gestión de médicos solicitada por el usuario.
* Redirigiendo a la página JSP correspondiente a la opción de menú requerida.
* @param sOpcion El código de la opción de menú solicitada por el usuario.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @throws
*/
private void evaluarOpcion(String sOpcion, HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws IOException
{
int nOpcion = 0;
try
{
nOpcion = Integer.parseInt(sOpcion);
}
catch(NumberFormatException e)
{
}
switch(nOpcion)
{
case OPC_MED_CABECERA:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Cabecera' seleccionada");
response.sendRedirect("../jsp/med/cabecera.jsp?x=0");
break;
}
case OPC_MED_PASSWORD:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Password' seleccionada");
response.sendRedirect("../jsp/med/password.jsp?x=1");
//response.sendRedirect("../jsp/pac/gestor.jsp");
break;
}
case OPC_MED_ACTOS:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Actos Médicos' seleccionada");
response.sendRedirect("../jsp/med/actos.jsp?x=2");
break;
}
case OPC_MED_LIQUIDACION:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Liquidación' seleccionada");
//Se trata de un analista. Se le redirecciona a la pagina de liquidación de analistas
if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA) ) {
response.sendRedirect("../jsp/med/liquidacion_analista.jsp?x=4&pagina=1");
//Se trata de un radiologo. Se le redirecciona a la pagina de liquidación de radiologos.
}
else if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO) ) {
response.sendRedirect("../jsp/med/liquidacion_radiologo.jsp?x=5&pagina=1");
//Se trata de un especialista o de un medico de cabecera. Se le redirecciona a la pagina de liquidación.
}
else{
response.sendRedirect("../jsp/med/liquidacion.jsp?x=3");
}
break;
}
case OPC_MED_PACIENTES:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Detalle de Pacientes' seleccionada");
response.sendRedirect("../jsp/med/pacientes.jsp?x=5");
break;
}
case OPC_MED_IRPF:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Detalle de I.R.P.F.' seleccionada");
response.sendRedirect("../jsp/med/irpf.jsp?x=6");
break;
}
case OPC_MED_MEDICAMENTOS:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Medicamentos' seleccionada");
response.sendRedirect("../jsp/med/medicamentos.jsp?x=8");
break;
}
case OPC_MED_PRESCRIPCIONES:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Prescripciones realizadas' seleccionada");
response.sendRedirect("../jsp/med/prescripciones.jsp?x=9");
break;
}
case OPC_MED_ANALISIS:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Análisis' seleccionada");
response.sendRedirect("../jsp/med/analisis.jsp?x=10");
break;
}
case OPC_MED_IGUALADOS:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Igualados' seleccionada");
response.sendRedirect("../jsp/med/igualados.jsp?x=12");
break;
}
case OPC_MED_PREAVISO:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Preaviso de caducidad de clave");
response.sendRedirect("../jsp/med/preaviso.jsp");
break;
}
case OPC_MED_PETICION_CAPTURADA:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se acepta el analisis prescrito");
this.introducirPacientePeticion(request, response, sesion);
response.sendRedirect("../jsp/med/peticiones_capturadas.jsp?x=17&exito=1");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_MED_PETICION_CAPTURADA: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error al introducir el paciente de la peticion capturada." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_MED_PETICION_CAPTURADA: " + ex);
sesion.setAttribute("ERROR", "Error al introducir el paciente de la peticion capturada.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_IMPRIMIR_PETICIONES:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Imprimir peticciones capturadas");
this.generarPDFPeticiones(request, response, sesion, OPC_MED_IMPRIMIR_PETICIONES);
DES encrypter = new DES(""+((Usuario)sesion.getAttribute("USUARIO")).getMedico());
String peticionEncriptada = encrypter.encrypt(""+((Usuario)sesion.getAttribute("USUARIO")).getMedico());
sesion.setAttribute("ENC", peticionEncriptada);
response.sendRedirect("../jsp/med/peticiones_capturadas.jsp?x=17&pagina=1&imp=1");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_MED_IMPRIMIR_PETICIONES: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la impresion de las peticiones capturadas." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_MED_IMPRIMIR_PETICIONES: " + ex);
sesion.setAttribute("ERROR", "Error en la impresion de las peticiones capturadas.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_GENERAR_DETALLE_IRPF:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Generar PDF del certificado de IRPF");
this.generarPDF_IRPF(request, response, sesion, OPC_MED_IMPRIMIR_PETICIONES);
DES encrypter = new DES(""+((Usuario)sesion.getAttribute("USUARIO")).getMedico());
String irpfEncriptado = encrypter.encrypt(""+((Usuario)sesion.getAttribute("USUARIO")).getMedico() + "_" + (String)request.getParameter("anio"));
sesion.setAttribute("ENC", irpfEncriptado);
response.sendRedirect("../jsp/med/detalleIRPF.jsp?x=7&imp=1");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_MED_GENERAR_DETALLE_IRPF: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la creación del certificado de IRPF." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_MED_GENERAR_DETALLE_IRPF: " + ex);
sesion.setAttribute("ERROR", "Error en la creación del certificado de IRPF.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_ACTUALIZAR_CABECERA: //actualizamos los datos del medico de cabecera
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se actualiza la informacion del medico de cabecera");
this.actualizarDatosMedicoCabecera(request, response, sesion);
//redirigimos a la pagina de cabecera
sesion.setAttribute("MSG", "Cambios guardados corréctamente.");
response.sendRedirect("../jsp/med/cabecera.jsp?x=" + request.getParameter("x"));
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la actualizacion de los datos del médico." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
sesion.setAttribute("ERROR", "Error en la actualizacion de los datos del médico.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_ACTUALIZAR_PASSWORD: //actualizamos el password del médico conectado
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se actualiza el password del medico conectado");
if (this.claveMedicoExiste(((Usuario)sesion.getAttribute("USUARIO")).getMedico(), (String)request.getParameter("clave_anterior"), false))
{
//Actualiza la password del usuario
this.actualizarPassword(request, response, sesion);
sesion.setAttribute("ERROR", "Se ha actualizado su clave correctamente");
//Redirige a la pagina de password de nuevo
//response.sendRedirect("../jsp/med/password.jsp?x=" + request.getParameter("x"));
//redirige a la página de pasar la tarjeta
response.sendRedirect("../jsp/pac/gestor.jsp");
}
else
{
LogTarisan.logger.log(NivelLog.INFO, "La clave anterior introducida no es correcta, no se puede actualizar a la nueva clave");
sesion.setAttribute("ERROR", "Clave anterior incorrecta, no se puede actualizar su nueva clave");
response.sendRedirect("../jsp/error.jsp");
}
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la actualizacion de la clave del medico." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
sesion.setAttribute("ERROR", "Error en la actualizacion de la clave del medico.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_ACTUALIZAR_ACCESO: //actualizamos la clave de acceso al aconectarse por primera vez
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se actualiza el password del medico conectado por ser el primer acceso a la aplicación");
if (this.claveMedicoExiste(((Usuario)sesion.getAttribute("USUARIO")).getMedico(), (String)request.getParameter("clave_nueva"), true))
{
LogTarisan.logger.log(NivelLog.INFO, "La nueva clave debe ser diferente a la clave ya existente, no se puede actualizar a la nueva clave");
sesion.setAttribute("ERROR", "La nueva clave debe ser diferente a la clave ya existente");
response.sendRedirect("../jsp/error.jsp");
}
else
{
//Actualiza la clave del primer acceso del usuario
this.actualizarAcceso(request, response, sesion);
//Redirige a la página inicial del usuario
if(((String)sesion.getAttribute("PERFIL")).compareTo(PERFIL_ADMINISTRADOR) == 0)
{
response.sendRedirect("./GestorAdministracion?OPCION=" + OPC_ADM_USUARIO_LISTA);
}
else
{
response.sendRedirect("./GestorMedicos?OPCION=" + OPC_MED_LIQUIDACION);
}
}
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la actualizacion de la clave por primer acceso del medico." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
sesion.setAttribute("ERROR", "Error en la actualizacion de la clave por primer acceso del medico.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_REGISTRAR_LOG_ANALISIS: //Registramos en la tabla TAREGLOG el movimiento realizado por el usuario. Visualizar un analisis.
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se graba en la tabla TAREGLOG el movimiento realizado por el usuario. Visualizar un analisis.");
String strAutorizacion = (String)request.getParameter("autorizacion");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
//indicamos la sentencia select utilizada para ver el analisis
StringBuffer strSql = new StringBuffer();
strSql.append("SELECT TARESANA.FECHA, ttclient.NOMBRE, ttclient.APELLIDOS, TARESANA.AUTORIZACION");
strSql.append(" FROM TARESANA, ttbenefi, ttclient");
strSql.append(" WHERE TARESANA.PRESCRIPTOR=");
strSql.append(intMedico);
strSql.append(" AND TARESANA.AUTORIZACION=");
strSql.append(strAutorizacion);
strSql.append(" AND TARESANA.COLEC=TABENEFI.COLEC");
strSql.append(" AND TARESANA.POLIZA=TABENEFI.POLIZA");
strSql.append(" AND TARESANA.ORDEN=TABENEFI.ORDEN");
strSql.append(" AND ttbenefi.CLIENTE=TTCLIENT.CLIENTE");
strSql.append(" and ttbenefi.fecha_baja is null");
strSql.append(" ORDER BY TARESANA.FECHA DESC");
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos el ultimo valor del campo correlativo de la tabla tareglog.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorCorrelativo = perTareglog.obtenerUltimoValorCorrelativo(intMedico, tsFechaUltimoAcceso);
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TARESANA", strSql.toString(), "");
//redirigimos para mostrar el correspondiente analisis
response.sendRedirect("../resultados/" + strAutorizacion + ".txt");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error al actualizar la tabla TAREGLOG." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
sesion.setAttribute("ERROR", "Error al actualizar la tabla TAREGLOG.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_ENVIAR_EMAIL:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Enviamos el email de la incidencia");
String mensaje = request.getParameter("MENSAJE");
String tarjeta = request.getParameter("TARJETA");
String correo = request.getParameter("correo");
String asunto = request.getParameter("ASUNTO");
String nombreAdjuntos = request.getParameter("nombreAdjuntos");
String introducir_email = request.getParameter("introducir_email");
if (introducir_email!=null){
response.sendRedirect("../jsp/med/cabecera.jsp?x=0&email=1");
}else{
JavaMail javaMail = new JavaMail();
javaMail.mandarCorreo(mensaje,tarjeta,correo,asunto,nombreAdjuntos);
/* Eliminar archivo adjunto si lo tiene */
File dir = new File(ParametrosConfiguracion.ruta_adjuntos+"/");
Vector<String> archivos = Utilidades.buscar_ficheros_recursivo(dir);
if (archivos != null) {
for (int f=0; f < archivos.size() ; f++) {
String path = archivos.elementAt(f);
LogTarisan.logger.log(NivelLog.DEBUG, "Eliminamos todos los adjuntos. Ruta de adjunto "+f+": " + path);
File adjunto = new File(path);
if(adjunto.exists())
{
adjunto.delete();
}
}
}
response.sendRedirect("../jsp/med/incidencia.jsp?x=20&msg=Incidencia Enviada Correctamente");
}
break;
}
default:
{
response.sendRedirect("../jsp/med/liquidacion.jsp");
break;
}
}
}
/**
* @throws Exception
* @throws IOException
* @throws ServletException
* Actualiza los datos de cabecera para el médico conectado a la aplicación.
* @param request Objeto <code>HttpServletRequest</code> que contiene los parámetros enviados desde la página Html.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> utilizado para actualizar el objeto usuario con los datos de cabecera del medico ya modificados.
* @throws
*/
private void actualizarDatosMedicoCabecera(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan, Exception
{
Object[] aValores=null;
Object[] aCondiciones=null;
Enumeration enumParametros=null;
int intNumValores=0;
int i;
String strParametro="";
StringBuffer strSql = new StringBuffer();
Vector vNombreCamposValores = new Vector();
try
{
strSql.append("UPDATE TAMEDICO");
//calculamos el tamaño de los arrays de los valores y condiciones para construir la sentencia sql
enumParametros = request.getParameterNames();
while (enumParametros.hasMoreElements())
{
strParametro=(String)enumParametros.nextElement();
if (strParametro.indexOf("valor_")!=-1) //se trata de un parametro valor
{
intNumValores++;
vNombreCamposValores.addElement(strParametro.substring(6));
}
}
//inicializamos los arrays con los valores y creamos la select
//array valores
strSql.append(" SET ");
aValores = new Object[intNumValores];
for(i=0;i<vNombreCamposValores.size();i++)
{
aValores[i] = request.getParameter("valor_" + (String)vNombreCamposValores.elementAt(i));
if (i<vNombreCamposValores.size() - 1) //no es ultimo elemento del vector
strSql.append((String)vNombreCamposValores.elementAt(i)).append(" = ?, ");
else //ultimo elemento del vector
strSql.append((String)vNombreCamposValores.elementAt(i)).append(" = ? ");
}
//array condiciones
strSql.append("WHERE MEDICO=?");
strSql.append(" AND ESPECIALIDAD=?");
aCondiciones = new Object[2];
aCondiciones[0] = Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getMedico() );
aCondiciones[1] = Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad() );
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones);
//actualizamos la variable de sesion de usuario
PersistenciaUsuario perUsuario = new PersistenciaUsuario();
Usuario usuario = perUsuario.seleccionar( ((Usuario)sesion.getAttribute("USUARIO")).getMedico(), ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad() );
Calendar calHoy = Calendar.getInstance();
usuario.setFechaUltAcceso(new Timestamp(calHoy.getTimeInMillis()));
sesion.setAttribute("USUARIO", usuario);
}
catch (ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
throw new ExcepcionTarisan(ex.getMessage());
}
}
/**
* Actualiza la clave asociada al médico conectado a la plicación.
* @param request Objeto <code>HttpServletRequest</code> que contiene los parámetros enviados desde la página Html.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> que contiene los datos del médico conectado a la aplicación.
* @throws
*/
private void actualizarPassword(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores = null;
Object[] aCondiciones = null;
StringBuffer strSql = new StringBuffer();
String strClaveNueva = (String)request.getParameter("clave_nueva");
Calendar calHoy = Calendar.getInstance();
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
try
{
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PASSWORD = ?");
strSql.append(" , FECHA_MODIF_CLAVE = ?");
strSql.append(" WHERE MEDICO = ?");
strSql.append(" AND ESPECIALIDAD = ?");
aValores = new Object[2];
aValores[0] = Utilidades.encripta(strClaveNueva, String.valueOf((((Usuario)sesion.getAttribute("USUARIO")).getMedico())));
aValores[1] = new Timestamp(calHoy.getTimeInMillis());
aCondiciones = new Object[2];
aCondiciones[0] = Integer.valueOf(((Usuario)sesion.getAttribute("USUARIO")).getMedico());
aCondiciones[1] = Integer.valueOf(((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad());
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
PersistenciaTamedico per = new PersistenciaTamedico();
per.modificarMedico(strSql.toString(), aValores, aCondiciones);
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos el ultimo valor del campo correlativo de la tabla tareglog.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorCorrelativo = perTareglog.obtenerUltimoValorCorrelativo(intMedico, tsFechaUltimoAcceso);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMEDICO", Utilidades.obtenerSentenciaSQL(strSql, aValores, aCondiciones), "", conexion);
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
}
catch (ExcepcionTarisan ex)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch (Exception ex)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex.getMessage());
throw new ExcepcionTarisan(ex.getMessage());
}
finally
{
//liberamos la conexion
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
}
catch (ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
throw new ExcepcionTarisan(ex.getMessage());
}
}
/**
* Actualiza la clave asociada al médico conectado a la aplicación cuando se trata del primer acceso a la misma.
* @param request Objeto <code>HttpServletRequest</code> que contiene los parámetros enviados desde la página Html.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> que contiene los datos del médico conectado a la aplicación.
* @throws
*/
private void actualizarAcceso(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores = null;
Object[] aCondiciones = null;
StringBuffer strSql = new StringBuffer();
String strClaveNueva = (String)request.getParameter("clave_nueva");
Calendar calHoy = Calendar.getInstance();
try
{
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PASSWORD = ?");
strSql.append(" , FECHA_MODIF_CLAVE = ?");
strSql.append(" , FECHA_ULT_ACCESO = ?");
strSql.append(" , BLOQUEO_CLAVE = ?");
strSql.append(" WHERE MEDICO = ?");
strSql.append(" AND ESPECIALIDAD = ?");
aValores = new Object[4];
aValores[0] = Utilidades.encripta(strClaveNueva, String.valueOf((((Usuario)sesion.getAttribute("USUARIO")).getMedico())));
aValores[1] = new Timestamp(calHoy.getTimeInMillis());
aValores[2] = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
aValores[3] = "N";
aCondiciones = new Object[2];
aCondiciones[0] = Integer.valueOf(((Usuario)sesion.getAttribute("USUARIO")).getMedico());
aCondiciones[1] = Integer.valueOf(((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad());
PersistenciaTamedico per = new PersistenciaTamedico();
per.modificarMedico(strSql.toString(), aValores, aCondiciones);
}
catch (ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
throw new ExcepcionTarisan(ex.getMessage());
}
}
/**
* Comprueba si es correcta o no la clave de usuario para el médico conectado.
* @param codigo El código de usuario conectado.
* @param clave La clave de usuario introducida en la página de cambio de password.
* @param primerAcceso Indicador de si es la primera vez que se conecta el usuario, para cifrar o no la clave.
* @return El valor booleano correspondiente a la existencia o no del registro.
* @throws
*/
private boolean claveMedicoExiste(int medico, String clave, boolean primerAcceso) throws ExcepcionTarisan
{
boolean resultado = false;
StringBuffer sqlSelect = new StringBuffer();
sqlSelect.append("SELECT * ");
sqlSelect.append("FROM TAMEDICO ");
sqlSelect.append("WHERE MEDICO = ? AND PASSWORD = ?");
try
{
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
Object aCondiciones[] = new Object[2];
aCondiciones[0] = Integer.valueOf(medico);
if(!primerAcceso)
{
aCondiciones[1] = Utilidades.encripta(clave, String.valueOf(medico));
}
else
{
aCondiciones[1] = clave;
}
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect.toString(), aCondiciones);
while(rs.next())
{
resultado = true;
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "Comprueba la corrección de la clave del usuario " + medico + " en la tabla TAMEDICO (" + sqlSelect + ")");
}
catch(SQLException sqle)
{
resultado = false;
LogTarisan.logger.log(NivelLog.ERROR, "Error en la comprobación de la corrección de la clave de usuario: " + sqle + " (" + sqlSelect + ")");
throw new ExcepcionTarisan();
}
catch (ExcepcionTarisan ex)
{
resultado = false;
LogTarisan.logger.log(NivelLog.ERROR, "Error en la comprobación de la corrección de la clave de usuario: " + ex.getMensaje() + " (" + sqlSelect + ")");
throw (ExcepcionTarisan)ex;
}
return resultado;
}
private void generarPDFPeticiones(HttpServletRequest request, HttpServletResponse response, HttpSession sesion, int tipoDoc) throws ExcepcionTarisan
{
try
{
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
PersistenciaTapecap per = new PersistenciaTapecap();
int medico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
int intEspe = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
PersistenciaTamedico perTame = new PersistenciaTamedico();
Tamedico tamedico = new Tamedico();
tamedico = perTame.seleccionar(medico);
//Fecha de busqueda
String strFecha = "";
if (request.getParameter("fec") != null) {
strFecha =(String)request.getParameter("fec");
}
Vector vSeleccion = per.imprimirPeticionesCapturadas(medico, strFecha, 1);
Tapecap tapecap = null;
tapecap = (Tapecap)vSeleccion.elementAt(0);
String strFechaPeticiones = tapecap.getFecha().toString();
String dia="";
String mes="";
String anio="";
dia = strFechaPeticiones.substring(8, 10);
mes = strFechaPeticiones.substring(5, 7);
anio = strFechaPeticiones.substring(0, 4);
String fechaBuena = dia+"/"+mes+"/"+anio;
sdfFormateadorFecha = new SimpleDateFormat("dd/MM/yyyy");
//Creamos el documento
Document document = new Document();
//Fijamos Márgenes
document.setMargins(40, 40, 5, 5);
// we create a writer that listens to the document
String strFile = "";
if (intEspe == ParametrosConfiguracion.analiticas){
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_analiticas_capturadas+((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";
}else if (intEspe == ParametrosConfiguracion.radiodiagnostico){
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_rx_capturados+((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";
}
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
document.open();
Print print = new Print();
Font fuente1= new Font();
fuente1.setSize(12);
//fuente1.setStyle(Font.BOLD);
Font fuente2= new Font();
fuente2.setSize(8);
Font fuente3= new Font();
fuente3.setSize(7);
Font fuente4= new Font();
fuente4.setSize(10);
//Definición de la tabla exterior
PdfPTable tableExterior = new PdfPTable(2); //Numero de comlumnas de la tabla
tableExterior.setWidthPercentage(100);
float[] headerWidths={50,620}; //Tamaño(Anchura) de las columnas
tableExterior.setWidths(headerWidths);
// Fecha
String txtFecha = fechaBuena;
// Si desea crear una celda de mas de una columna. Cree un objecto Cell y cambie su propiedad span
PdfPCell celdaFecha = new PdfPCell(new Paragraph(" FECHA: " + txtFecha,fuente4));
celdaFecha.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaFecha.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaFecha);
// Titulo
String strNom = "";
if (tamedico.getNombre()!=null){
strNom = ""+tamedico.getNombre();
}
String strApe = "";
if (tamedico.getApellidos()!=null){
strApe = ""+tamedico.getApellidos();
}
String txtMedico = strNom + " " + strApe;
PdfPCell celdaTitulo = new PdfPCell(new Paragraph(txtMedico,fuente1));
celdaTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaTitulo.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTitulo);
//Celda en blanco
PdfPCell celdaLibre = new PdfPCell(new Paragraph(" ",fuente1));
celdaLibre.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaLibre.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaLibre);
// Peticiones aceptadas
for(int i = 0; i < vSeleccion.size(); i++)
{
tapecap = (Tapecap)vSeleccion.elementAt(i);
String strCodigo = "" + tapecap.getCodigo();
String strColec = "";
if (tapecap.getColectivo()!=-1){
strColec = ""+tapecap.getColectivo();
}
String strBen = "";
if (tapecap.getOrden()!=-1){
strBen = ""+tapecap.getOrden();
}
String iden = "";
if (tapecap.getIdentificador()!=null){
iden = ""+tapecap.getIdentificador();
}
String pol = "";
if (tapecap.getPoliza()!=-1){
pol = ""+tapecap.getPoliza();
}
String aut = "";
if (tapecap.getAutorizacion()!=-1){
aut = ""+tapecap.getAutorizacion();
}
String strPrescriptor = "";
if (tapecap.getPrescriptor()!=null){
strPrescriptor = ""+tapecap.getPrescriptor();
}
String strEspe = "";
if (tapecap.getEspecialidad()!=null){
strEspe = ""+tapecap.getEspecialidad();
}
String strDireccion = "";
if (tapecap.getDireccion()!=null){
strDireccion = ""+tapecap.getDireccion();
}
String strDni = "";
if (tapecap.getNif()!=null){
strDni = ""+tapecap.getNif();
}
String strNobre = "";
if (tapecap.getNombre()!=null){
strNobre = ""+tapecap.getNombre();
}
String strApellidos = "";
if (tapecap.getApellidos()!=null){
strApellidos = ""+tapecap.getApellidos();
}
String strCompania = "";
if (tapecap.getCompania()!=null){
strCompania = ""+tapecap.getCompania();
}
String strTelefono = "";
if (tapecap.getTelefono()!=null){
strTelefono = ""+tapecap.getTelefono();
}
String fechaNac = "";
if (tapecap.getFecha_nac()!=null){
fechaNac = ""+tapecap.getFecha_nac();
String d = "";
String m = "";
String a = "";
d = fechaNac.substring(8, 10);
m = fechaNac.substring(5, 7);
a = fechaNac.substring(0, 4);
fechaNac = d+"/"+m+"/"+a;
}
String strColPolOrd = "";
if((tapecap.getColectivo()!=-1)||(tapecap.getPoliza()!=-1)||(tapecap.getOrden()!=-1)){
strColPolOrd = strColec + " - " + pol + " - " + strBen;
}
PdfPTable tableInterior = new PdfPTable(2);
float[] headerWidths2={350,300}; //Tamaño(Anchura) de las columnas
tableInterior.setWidths(headerWidths2);
tableInterior.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
tableInterior.addCell(new Paragraph("NOMBRE: " + strNobre.trim() + " " + strApellidos.trim(),fuente2));
tableInterior.addCell(new Paragraph("COMPAÑIA: " + strCompania.trim(),fuente2));
tableInterior.addCell(new Paragraph("DIRECción: " + strDireccion.trim(),fuente2));
tableInterior.addCell(new Paragraph("Nº PÓLIZA: " + strColPolOrd,fuente2));
tableInterior.addCell(new Paragraph("FECHA NACIMIENTO: " + fechaNac,fuente2));
tableInterior.addCell(new Paragraph("AUTORIZAción: " + aut,fuente2));
tableInterior.addCell(new Paragraph("DNI: " + strDni,fuente2));
tableInterior.addCell(new Paragraph("PETICIONARIO: DR(a). " + strPrescriptor.trim(),fuente2));
tableInterior.addCell(new Paragraph("TELEFONO: " + strTelefono,fuente2));
tableInterior.addCell(new Paragraph("ESPECIALIDAD: " + strEspe.trim(),fuente2));
tableInterior.addCell(new Paragraph("TARJETA: " + iden,fuente2));
tableInterior.addCell(new Paragraph("",fuente2));
PdfPTable tableCodigo = new PdfPTable(1);
tableCodigo.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
tableCodigo.addCell(new Paragraph("CODIGO",fuente3));
tableCodigo.addCell(new Paragraph(" ",fuente3));
tableCodigo.addCell(new Paragraph(" " + strCodigo,fuente1));
tableExterior.addCell(tableCodigo);
tableExterior.addCell(tableInterior);
}
document.add(tableExterior);
//CERRAR DOCUMENTO
// step 5: we close the document
document.close();
} catch (Exception ex) {
System.out.println("Excepcion" + ex);
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion al generarPDF: "+ex.toString());
}
}
private void generarPDF_IRPF(HttpServletRequest request, HttpServletResponse response, HttpSession sesion, int tipoDoc) throws ExcepcionTarisan
{
try
{
/*SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat("dd/MM/yyyy");*/
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
PersistenciaTadremed per = new PersistenciaTadremed();
int medico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
PersistenciaTamedico perTame = new PersistenciaTamedico();
Tamedico tamedico = new Tamedico();
tamedico = perTame.seleccionar(medico);
//año de búsqueda
String strAnio = "";
if (request.getParameter("anio") != null) {
strAnio =(String)request.getParameter("anio");
}
Vector vSeleccion = per.ObtenerTotalesIrpf(medico, strAnio);
Tadremed tadremed = null;
tadremed = (Tadremed)vSeleccion.elementAt(0);
String strFechaHoy = dtFecha.toString();
String dia="";
String mes="";
String anio="";
dia = strFechaHoy.substring(8, 10);
mes = strFechaHoy.substring(5, 7);
anio = strFechaHoy.substring(0, 4);
String mesEscrito = "";
switch (Integer.parseInt(mes)) {
case 1: mesEscrito = "Enero";
break;
case 2: mesEscrito = "Febrero";
break;
case 3: mesEscrito = "Marzo";
break;
case 4: mesEscrito = "Abril";
break;
case 5: mesEscrito = "Mayo";
break;
case 6: mesEscrito = "Junio";
break;
case 7: mesEscrito = "Julio";
break;
case 8: mesEscrito = "Agosto";
break;
case 9: mesEscrito = "Septiembre";
break;
case 10: mesEscrito = "Octubre";
break;
case 11: mesEscrito = "Noviembre";
break;
case 12: mesEscrito = "Diciembre";
break;
}
/*sdfFormateadorFecha = new SimpleDateFormat("dd/MM/yyyy");*/
Document document = new Document();
document.setMargins(70, 70, 5, 5);
String strFile = "";
strFile = ParametrosConfiguracion.ruta_pdf_irpf+((Usuario)sesion.getAttribute("USUARIO")).getMedico() + "_" + strAnio + ".pdf";
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
document.open();
/*Print print = new Print();*/
String rutaRaleway = this.getServletContext().getRealPath(File.separator)+"fonts/Raleway-Light.ttf";
String rutaRalewayNegrita = this.getServletContext().getRealPath(File.separator)+"fonts/Raleway-Bold.ttf";
BaseFont raleway = BaseFont.createFont(rutaRaleway, BaseFont.WINANSI, BaseFont.EMBEDDED);
BaseFont ralewayNegrita = BaseFont.createFont(rutaRalewayNegrita, BaseFont.WINANSI, BaseFont.EMBEDDED);
Font fuente1= new Font(ralewayNegrita);
fuente1.setSize(11);
/*fuente1.setStyle(Font.BOLD);*/
Font fuente2= new Font(raleway);
fuente2.setSize(11);
/*fuente2.setFamily("HELVETIA");*/
//Definición de la tabla exterior
PdfPTable tableExterior = new PdfPTable(2); //Numero de comlumnas de la tabla
tableExterior.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
tableExterior.setWidthPercentage(100);
float[] headerWidths={50,620}; //Tamaño(Anchura) de las columnas
tableExterior.setWidths(headerWidths);
//Celda en blanco
PdfPCell celdaLibre = new PdfPCell(new Paragraph(" ",fuente1));
celdaLibre.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaLibre.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
// Titulo Margen Derecho
String strNom = "";
if (tamedico.getNombre()!=null){
strNom = ""+tamedico.getNombre();
strNom = strNom.trim();
}
String strApe = "";
if (tamedico.getApellidos()!=null){
strApe = ""+tamedico.getApellidos();
strApe = strApe.trim();
}
String strDireccion = "";
if (tamedico.getDireccionCab()!=null){
strDireccion = ""+tamedico.getDireccionCab();
}
String strCp = "";
if (tamedico.getCpCab() != 0){
strCp = ""+tamedico.getCpCab() + " - ";
}
String strPoblacion = "";
if (tamedico.getPoblacionCab()!=null){
strPoblacion = ""+tamedico.getPoblacionCab();
}
String NombreCompleto = strNom + " " + strApe;
// Si desea crear una celda de mas de una columna. Cree un objecto Cell y cambie su propiedad span
PdfPCell celdaNombre = new PdfPCell(new Paragraph(" " + NombreCompleto,fuente2));
celdaNombre.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaNombre.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaDireccion = new PdfPCell(new Paragraph(" " + strDireccion,fuente2));
celdaDireccion.setColspan(2);
celdaDireccion.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaPoblacion = new PdfPCell(new Paragraph(" " + strCp + strPoblacion,fuente2));
celdaPoblacion.setColspan(2);
celdaPoblacion.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaNombre);
tableExterior.addCell(celdaDireccion);
tableExterior.addCell(celdaPoblacion);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
String textoA1= "D. DANIEL CAMARA BAZTAN, con DNI 72.805.898 L, Director General de";
String textoA2= "IGUALATORIO Médico DE NAVARRA, S.A., con NIF A-31005432 y con domicilio en";
String textoA3= "Pamplona, Avenida Bayona, 4 - Bajo,";
PdfPCell celdaTexto1 = new PdfPCell(new Paragraph(textoA1,fuente1));
celdaTexto1.setColspan(2);
celdaTexto1.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaTexto2 = new PdfPCell(new Paragraph(textoA2,fuente1));
celdaTexto2.setColspan(2);
celdaTexto2.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaTexto3 = new PdfPCell(new Paragraph(" "+textoA3,fuente1));
celdaTexto3.setColspan(2);
celdaTexto3.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTexto1);
tableExterior.addCell(celdaTexto2);
tableExterior.addCell(celdaTexto3);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
PdfPCell celdaCertifico = new PdfPCell(new Paragraph("C E R T I F I C O:",fuente1));
celdaCertifico.setColspan(2);
celdaCertifico.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaCertifico);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
Phrase parte1=new Phrase("Que, ",fuente2);
Phrase parte2=new Phrase(NombreCompleto,fuente1);
Phrase parte3=new Phrase(" ha percibido durante el ejercicio del año ",fuente2);
Phrase parte4=new Phrase(strAnio,fuente1);
Phrase parte5=new Phrase(" en concepto de Honorarios Médicos, la cantidad de:",fuente2);
Phrase lineaEntera=new Phrase();
lineaEntera.add(parte1);
lineaEntera.add(parte2);
lineaEntera.add(parte3);
lineaEntera.add(parte4);
lineaEntera.add(parte5);
lineaEntera.setLeading(40);
PdfPCell celdaTextoB1 = new PdfPCell(lineaEntera);
celdaTextoB1.setLeading(15f, 0f);
/*celdaTextoB1.setIndent(50f);*/
celdaTextoB1.setColspan(2);
celdaTextoB1.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTextoB1);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
PdfPCell celdaTotal = new PdfPCell(new Paragraph("Total bruto: "+ tadremed.getImporteTotal() + " €",fuente1));
celdaTotal.setColspan(2);
celdaTotal.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaRetencion = new PdfPCell(new Paragraph("Retención: "+ tadremed.getIrpfTotal() + " €",fuente1));
celdaRetencion.setColspan(2);
celdaRetencion.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTotal);
tableExterior.addCell(celdaRetencion);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
String textoC1 = "Y para que conste y sirva de justificante al interesado ante la Delegación de Hacienda";
String textoC2 = "expido el presente certificado en Pamplona a "+dia+" de "+mesEscrito+" de "+anio+".";
PdfPCell celdaTextoC1 = new PdfPCell(new Paragraph(textoC1,fuente2));
celdaTextoC1.setColspan(2);
celdaTextoC1.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaTextoC2 = new PdfPCell(new Paragraph(textoC2,fuente2));
celdaTextoC2.setColspan(2);
celdaTextoC2.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTextoC1);
tableExterior.addCell(celdaTextoC2);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
document.add(tableExterior);
/*Image imagen = Image.getInstance("/root/apache-tomcat-6.0.20/webapps/tarisan/img/firma.jpg"); */
Image imagen = Image.getInstance(ParametrosConfiguracion.ruta_img+"firma_daniel.png");
imagen.setAlignment(Element.ALIGN_CENTER);
imagen.scaleAbsolute(120, 100);
document.add(imagen);
document.close();
} catch (Exception ex) {
System.out.println("Excepcion" + ex);
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion al generarPDF: "+ex.toString());
}
}
private void introducirPacientePeticion(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
try
{
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
PersistenciaTapecap perTapecap = new PersistenciaTapecap();
//obtenemos los datos del medico y del paciente
long longAutorizacion = Long.parseLong( (String)request.getParameter("autorizacion") );
String strApellidos = (String)request.getParameter("apellidos");
String strNombre = (String)request.getParameter("nombre");
String strNif = (String)request.getParameter("dni");
String strDireccion = (String)request.getParameter("direccion");
String strFechaNac = (String)request.getParameter("fec_nac");
String strTelefono = (String)request.getParameter("telefono");
String strCompania = (String)request.getParameter("compania");
String strIdentificador = (String)request.getParameter("identificador");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
String strPrescriptor = (String)request.getParameter("medico");
String strEspecialidad = (String)request.getParameter("espe");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Calendar fecha = Calendar.getInstance();
Timestamp fechaAcceso = new Timestamp(fecha.getTimeInMillis());
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
/*String [] arrayLetras = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "Ñ", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
String letra="";
String strNumero = "";
String strCodigo="";*/
//obtenemos el ultimo valor del campo correlativo de la tabla tareglog.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorCorrelativo = perTareglog.obtenerUltimoValorCorrelativo(intMedico, tsFechaUltimoAcceso);
//obtenemos el ultimo valor del campo codigo de la tabla tapecap.
//Este campo es un numero correlativo utilizado para diferenciar las peticiones capturadas por medico y dia.
int intUltimoValorCodigo = perTapecap.obtenerUltimoCodigo(intMedico);
/*if (perTapecap.existePaciente(intMedico, strIdentificador)){
int num = 0;
strCodigo = perTapecap.obtenerUltimoCodigoMismoPaciente(intMedico,strIdentificador);
letra = strCodigo.substring(0, 1);
strNumero = strCodigo.substring(1);
num = Integer.parseInt(strNumero) + 1;
strCodigo = letra + num;
}else{
strCodigo = perTapecap.obtenerUltimoCodigo(intMedico);
if (strCodigo.compareTo("")==0 ){
strCodigo = "A1";
}else{
letra = strCodigo.substring(0, 1);
int pos = 0;
for (int i=0; i < arrayLetras.length; i ++){
if (letra.compareTo(arrayLetras[i])==0 ){
pos = i + 1;
}
}
letra = arrayLetras[pos];
strNumero = "1";
strCodigo = letra + strNumero;
}
}*/
/*double intUltimoValorCodigo = 0;
if (perTapecap.existePaciente(intMedico, strIdentificador)){
intUltimoValorCodigo = perTapecap.obtenerUltimoCodigoMismoPaciente(intMedico,strIdentificador);
intUltimoValorCodigo = intUltimoValorCodigo+ (0.1);
}else{
intUltimoValorCodigo = perTapecap.obtenerUltimoCodigo(intMedico);
intUltimoValorCodigo = intUltimoValorCodigo+1;
}*/
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
//introducimos un nuevo registro en la tabla tapecap
strSql = new StringBuffer();
strSql.append("INSERT INTO TAPECAP");
strSql.append(" (TAPECAP_PK, CODIGO, FECHA, APELLIDOS, NOMBRE, NIF, DIRECCION, FECHA_NAC, TELEFONO, COMPAÑIA, IDENTIFICADOR, MEDICO, AUTORIZACION, PRESCRIPTOR, ESPECIALIDAD, POLIZA, COLECTIVO, ORDEN)");
strSql.append(" SELECT TAPECAP_PK_SEQ.NEXTVAL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM DUAL");
//cargamos el array
aValores = new Object[17];
aValores[0] = intUltimoValorCodigo;
aValores[1] = (String)Utilidades.formatear_fecha(dtFecha);
aValores[2] = (String)strApellidos;
aValores[3] = (String)strNombre;
aValores[4] = (String)strNif;
aValores[5] = (String)strDireccion;
aValores[6] = (String)strFechaNac;
aValores[7] = (String)strTelefono;
aValores[8] = (String)strCompania;
aValores[9] = strIdentificador;
aValores[10] = intMedico;
aValores[11] = longAutorizacion;
aValores[12] = strPrescriptor;
aValores[13] = strEspecialidad;
aValores[14] = -1;
aValores[15] = -1;
aValores[16] = -1;
perTapecap.insertarPeticionCapturada(strSql.toString(), aValores, conexion);
perTareglog.insertarLog(intMedico, fechaAcceso, Calendar.getInstance(), intUltimoValorCorrelativo+1, "TAPECAP", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
}
catch (ExcepcionTarisan ex)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch (Exception ex)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex.getMessage());
throw new ExcepcionTarisan(ex.getMessage());
}
finally
{
//liberamos la conexion
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
}
catch (ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: " + ex.getMensaje());
throw (ExcepcionTarisan)ex;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Exception: " + ex);
throw new ExcepcionTarisan(ex.getMessage());
}
}
}