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

8421 lines
390 KiB
Java

/**
* @(#) GestorPacientes.java
*/
package com.tarisan.servlets;
import com.itextpdf.text.*;
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.itextpdf.text.pdf.draw.LineSeparator;
import com.tarisan.control.*;
import com.tarisan.persistencia.OracleParametros;
import com.tarisan.persistencia.PersistenciaParametros;
import com.tarisan.data.Paciente;
import com.tarisan.data.RespuestaChipcard;
import com.tarisan.data.Tadespla;
import com.tarisan.data.Tamensaje;
import com.tarisan.data.Tapresca;
import com.tarisan.data.Tarjeta;
import com.tarisan.data.Tavolin;
import com.tarisan.data.Usuario;
import com.tarisan.data.Tamedico;
import com.tarisan.data.VTamovextTaclient;
import com.tarisan.excepcion.*;
import com.tarisan.log.*;
import com.tarisan.util.DES;
import com.tarisan.util.Print;
import com.tarisan.util.Utilidades;
import com.tarisan.chipcard.tpvvs.ws.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Calendar;
import java.util.StringTokenizer;
import java.util.Vector;
import java.sql.*;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
/**
* Servlet direccionador a páginas JSP para el módulo de gestión de pacientes.
* @author <a href="mailto:sistemas@imqnavarra.com">Dpto. Informática</a>.
* @version 1.0, 24/09/2003
*/
public class GestorPacientes extends HttpServlet implements Constantes
{
/**
* Recepción de la petición de acceso al módulo de gestión de pacientes solicitada por el cliente.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que recibirá el cliente.
*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
LogTarisan.logger.log(NivelLog.INFO, "GestorPacientes.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
{
LogTarisan.logger.log(NivelLog.DEBUG, "Entrada aceptada al módulo de Gestión de Pacientes");
String opcion = "";
if (request.getParameter("OPCION") != null) {
opcion = request.getParameter("OPCION");
}
this.evaluarOpcion(opcion, request, response, sesion);
}
LogTarisan.logger.log(NivelLog.INFO, "GestorPacientes.service().FIN");
}
//Metodo que devuelve la posicion a la que se coloca un texto para que quede ajustado a la derecha
//Se le pasa por parametro el texto a ajustar y la posicion a la que se quiere ajustar
private int ajustarTextoADerecha(String texto, int posicion){
int longitudTexto = 0;
int pos = 0;
longitudTexto = texto.length();
pos = posicion - (longitudTexto*6);
return pos;
}
private void generarPDFViejo(HttpServletRequest request, HttpServletResponse response, HttpSession sesion, int tipoDoc) throws ExcepcionTarisan
{
String strTexto = "";
LogTarisan.logger.log(NivelLog.DEBUG, "generarPDF - Empieza - TipoDoc: "+tipoDoc);
try
{
String strMedico = ((Usuario)sesion.getAttribute("USUARIO")).getNombreCab().toString();
String strDireccion = ((Usuario)sesion.getAttribute("USUARIO")).getDireccionCab().toString();
String strEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidadCab().toString();
String strPoblacion = ((Usuario)sesion.getAttribute("USUARIO")).getPoblacionCab();
String strNumColegiado = "Num. Colegiado: " + ((Usuario)sesion.getAttribute("USUARIO")).getColegiadoCab().toString();
String strTelefono = ((Usuario)sesion.getAttribute("USUARIO")).getTelefonoCab().toString();
String strIngreso = (String)request.getParameter("num_ingreso");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 191");
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String strMensajeSinElementos="No ha seleccionado ningún acto médico.";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 195");
// ArrayList que contedrá las descripciones de analíticas
ArrayList arrayListaElementosPrescripcion = null;
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 198");
//Arraylist que tiene el número de actos...
ArrayList arrayListaUnidades = new ArrayList();
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 201");
String strAutorizacion = "";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 204: request.getAttribute(\"autorizacion\") = "+request.getAttribute("autorizacion"));
if (request.getAttribute("modifiAuto") != null && request.getAttribute("modifiAuto").toString().compareTo("")!=0) {
if (request.getAttribute("modifiAuto") != null) {
if(request.getAttribute("modifiAuto").getClass() == Long.class)
{
strAutorizacion = String.valueOf(request.getAttribute("modifiAuto"));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 210: strAutorizacion"+strAutorizacion);
}
else
{
strAutorizacion = (String)request.getAttribute("modifiAuto");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 215: strAutorizacion"+strAutorizacion);
}
}
}else{
if (request.getAttribute("autorizacion") != null) {
if(request.getAttribute("autorizacion").getClass() == Long.class)
{
strAutorizacion = String.valueOf(request.getAttribute("autorizacion"));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 210: strAutorizacion"+strAutorizacion);
}
else
{
strAutorizacion = (String)request.getAttribute("autorizacion");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 215: strAutorizacion"+strAutorizacion);
}
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 219");
String strInforme = "";
if (request.getParameter("informePrescripcion") != null) {
strInforme =(String)request.getParameter("informePrescripcion");
}
else if(request.getParameter("diagnostico") != null)
{
strInforme = (String)request.getParameter("diagnostico");
}
String strListaElementosPrescripcion = "";
String strListaElementosPrescripcionAux = "";
String strListaUnidades = "";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 233");
if (request.getParameter("listaElementosPrescripcion") != null ) {
// Lista de elementos de Prescripción
LogTarisan.logger.log(NivelLog.DEBUG, "Se van a insertar los siguientes codigos de analitica: "+(String)request.getParameter("listaCodigoElementosPrescripcion"));
strListaElementosPrescripcion = (String)request.getParameter("listaElementosPrescripcion");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
}
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
strListaElementosPrescripcionAux = strListaElementosPrescripcion.replace('\'', '~');
}
strListaElementosPrescripcion = strListaElementosPrescripcionAux;
while(strListaElementosPrescripcion.indexOf("~") != -1) {
strListaElementosPrescripcion = strListaElementosPrescripcion.replace('~','\'');
}
// Vector vElementosPrescripcion = new Vector();
arrayListaElementosPrescripcion = new ArrayList();
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 246");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
// Lista no vacía
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
//Separamos las diferentes determinaciones
int i = 0;
while (strListaElementosPrescripcion.indexOf("¬") != -1) {
arrayListaElementosPrescripcion.add(strListaElementosPrescripcion.substring(0, strListaElementosPrescripcion.indexOf("¬")));
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
i++;
}
if (i==0){
arrayListaElementosPrescripcion.add(strListaElementosPrescripcion);
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 259");
ArrayList temp = new ArrayList();
strListaUnidades = (String)request.getParameter("unidadesElementosPrescripcion");
if(strListaUnidades != null)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 261"+strListaUnidades);
strListaUnidades = strListaUnidades.substring(1);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 264");
while(strListaUnidades.indexOf("¬") != -1)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 267");
arrayListaUnidades.add(strListaUnidades.substring(0, strListaUnidades.indexOf("¬")));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 269: - "+strListaUnidades.substring(0, strListaUnidades.indexOf("¬")));
strListaUnidades = strListaUnidades.substring(strListaUnidades.indexOf("¬") + 1);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 271");
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 274");
for(int i = 0; i<arrayListaElementosPrescripcion.size(); i++)
{
temp.add(arrayListaElementosPrescripcion.get(i) + " - Uds: " + arrayListaUnidades.get(i));
}
arrayListaElementosPrescripcion = temp;
}
}
Collections.sort(arrayListaElementosPrescripcion);
String strListaCodigoElementos = "";
if (request.getParameter("listaCodigoElementosPrescripcion")!=null) {
strListaCodigoElementos=(String)request.getParameter("listaCodigoElementosPrescripcion");
}
//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 (tipoDoc == OPC_PAC_PRESCRIPCION_FACTURACION) {
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_facturas + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + "_" + ((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza() + ".pdf";
//strFile = Utilidades.Nombre_fact_pdf(((Usuario)sesion.getAttribute("USUARIO")).getMedico(), 1);
} else if ( tipoDoc == OPC_PAC_PRESCRIPCION_RECETAS)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_recetas + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() /*+ "_" + ((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza() */+ ".pdf";
} else if (tipoDoc == OPC_PAC_VOLANTE_INGRESO)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_ingresos + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() /*+ "_" + ((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza()*/ +".pdf";
}else if ( tipoDoc == OPC_PAC_PRESCRIPCION_DIAGNOSTICO)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_rx + strAutorizacion + ".pdf";
} else if ( tipoDoc == OPC_PAC_PRESCRIPCION_ANALITICA)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_analiticas + strAutorizacion + ".pdf";
} else if (tipoDoc == OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_ap + strAutorizacion + ".pdf";
}else if ( tipoDoc == OPC_PAC_PRESCRIPCION_ESPECIALIDADES)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_especialidades + strAutorizacion + ".pdf";
}else if (tipoDoc == OPC_PAC_PRESCRIPCION_ATS)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_ats + strAutorizacion + ".pdf";
}else if (tipoDoc == OPC_PAC_PETICION_AUTORIZACION)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_autorizaciones + strAutorizacion + ".pdf";
}else {
/*strFile = ParametrosConfiguracion.ruta_pdf + strAutorizacion + ".pdf";*/
/*strFile = "/root/peticiones/" + strAutorizacion + ".pdf";*/
strFile = "/var/lib/tomcat/webapps/tarisan/peticiones/" + strAutorizacion + ".pdf";
}
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
document.open();
// DIBUJAMOS EL TEXTO //
PdfContentByte cb = writer.getDirectContent();
cb.stroke();
BaseFont bf = BaseFont.createFont();
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false); //Poner en negrita
cb.beginText();
cb.setFontAndSize(bf, 18);
/* BaseColor bc = new BaseColor(10,100,10); //Letra en color
cb.setColorFill(bc);*/
//Creamos el separador (Para insertar las lineas posteriormente)
LineSeparator ls = new LineSeparator();
int pos = 0; // Variable en la que guardamos la posicion que utilizamos para ajustar textos a la derecha
//Creamos el objeto generador de PDF
Print print = new Print();
//AÑADIR CABECERA
switch(tipoDoc){
case OPC_PAC_PRESCRIPCION_DIAGNOSTICO:
{
strTexto = "Petición diagnóstico";
break;
}
case OPC_PAC_PRESCRIPCION_ANALITICA:
{
strTexto = "Petición Analítica";
break;
}
case OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA:
{
strTexto = "Petición Anatomía Patológica";
break;
}
case OPC_PAC_PRESCRIPCION_FACTURACION:
{
strTexto = "Impresión Facturación";
break;
}
case OPC_PAC_PETICION_AUTORIZACION:
{
strTexto = "Petición Autorización";
break;
}
case OPC_PAC_PRESCRIPCION_ESPECIALIDADES:
{
strTexto = "Impresión Especialidades";
break;
}
case OPC_PAC_PRESCRIPCION_RECETAS:
{
strTexto = "Impresión Recetas";
break;
}
case OPC_PAC_VOLANTE_INGRESO:
{
strTexto = "Autorización";
break;
}
case OPC_PAC_PRESCRIPCION_ATS:
{
strTexto = "Actos ATS";
break;
}
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strTexto, 330, 800, 0); // (align, texto, X, Y, Rotacion)
//AÑADIR LOGOTIPO
int intMedico=((Usuario)sesion.getAttribute("USUARIO")).getMedico();
document = print.anadirLogotipo(document, intMedico,45,780);
cb.setFontAndSize(bf, 10);
//AÑADIR MEDICOPRESCRIPTOR
if (tipoDoc != OPC_PAC_PRESCRIPCION_FACTURACION) {
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Medico:", 50, 750, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, 745); //Creamos una linea (posicion x inicio, posicion x fin, posicion y)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strMedico, 50, 730, 0);
pos = ajustarTextoADerecha(strDireccion, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strDireccion, pos, 730, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strEspecialidad, 50, 715, 0);
pos = ajustarTextoADerecha(strPoblacion, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoblacion, pos, 715, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strNumColegiado, 50, 700, 0);
pos = ajustarTextoADerecha(strTelefono, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strTelefono, pos, 700, 0);
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 341");
//AÑADIR PACIENTE
String strNomPaciente = "";
String strColectivo = "";
String strBeneficiario = "";
String strPoliza = "";
PersistenciaPaciente per = new PersistenciaPaciente();
String strfecnac = "00/00/0000";
Calendar fecnac = Calendar.getInstance();
String strnif = "";
if(sesion.getAttribute("PACIENTE") == null)
{
LogTarisan.logger.log(NivelLog.DEBUG, "No hay paciente en sesión, lo cojemos de los parámetros.");
strNomPaciente = (String)request.getParameter("nom_paciente");
LogTarisan.logger.log(NivelLog.DEBUG, "354");
strPoliza = (String)request.getParameter("poliza");
LogTarisan.logger.log(NivelLog.DEBUG, "356");
Tarjeta tar = new Tarjeta();
LogTarisan.logger.log(NivelLog.DEBUG, "358"+(String)request.getParameter("tarjeta"));
tar.setTarjeta(Integer.valueOf((String)request.getParameter("tarjeta")));
LogTarisan.logger.log(NivelLog.DEBUG, "360");
fecnac = per.obtenerFechaNacimiento(tar,((Usuario)sesion.getAttribute("USUARIO")).getMedico());
if(fecnac != null)
strfecnac = fecnac.get(Calendar.DAY_OF_MONTH)+"/"+(fecnac.get(Calendar.MONTH)+1)+"/"+fecnac.get(Calendar.YEAR);
strnif = per.obtenerNIF(tar,((Usuario)sesion.getAttribute("USUARIO")).getMedico());
}
else
{
strNomPaciente = ((Paciente)sesion.getAttribute("PACIENTE")).getNombre();
strColectivo = Long.toString( ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo());
strBeneficiario = Integer.toString(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario());
strPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo() +" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
fecnac = per.obtenerFechaNacimiento(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
if(fecnac != null)
strfecnac = fecnac.get(Calendar.DAY_OF_MONTH)+"/"+(fecnac.get(Calendar.MONTH)+1)+"/"+fecnac.get(Calendar.YEAR);
strnif = per.obtenerNIF(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
}
sdfFormateadorFecha = new SimpleDateFormat("dd/MM/yyyy");
dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
strPoblacion += ", " + sdfFormateadorFecha.format(dtFecha);
int posicionY = 0;
//IMPRIMIR PACIENTE
if (tipoDoc == OPC_PAC_PRESCRIPCION_FACTURACION || tipoDoc == OPC_PAC_PRESCRIPCION_RECETAS) {
posicionY = 750;
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Paciente:", 50, posicionY, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 5);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strNomPaciente, 50, posicionY - 20, 0);
}
if (strPoliza != null && strPoliza.length() > 0) {
pos = ajustarTextoADerecha(strPoliza, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoliza, pos, posicionY - 20, 0);
}
if (strPoblacion != null && strPoblacion.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoblacion, 50, posicionY - 35, 0);
}
if (strfecnac != null && strfecnac.length() > 0) {
pos = ajustarTextoADerecha("Fecha Nacimiento: "+strfecnac, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Fecha Nacimiento: "+strfecnac, pos, posicionY - 35, 0);
}
if (strnif != null && strnif.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strnif, 50, posicionY - 50, 0);
}
posicionY = posicionY - 95;
} else if (tipoDoc == OPC_PAC_PETICION_AUTORIZACION || tipoDoc == OPC_PAC_PRESCRIPCION_ATS) {
posicionY = 670;
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Paciente:", 50, posicionY, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 5);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strNomPaciente, 50, posicionY - 20, 0);
}
if (strPoliza != null && strPoliza.length() > 0) {
pos = ajustarTextoADerecha(strPoliza, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoliza, pos, posicionY - 20, 0);
}
if (strAutorizacion != null && strAutorizacion.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Num. Solicitud: " + strAutorizacion, 50, posicionY - 35, 0);
}
if (strPoblacion != null && strPoblacion.length() > 0) {
pos = ajustarTextoADerecha(strPoblacion, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoblacion, pos, posicionY - 35, 0);
}
posicionY = posicionY - 80;
} else if (tipoDoc == OPC_PAC_VOLANTE_INGRESO){
posicionY = 670;
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Paciente:", 50, posicionY, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 5);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strNomPaciente, 50, posicionY - 20, 0);
}
if (strPoliza != null && strPoliza.length() > 0) {
pos = ajustarTextoADerecha(strPoliza, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoliza, pos, posicionY - 20, 0);
}
if (strPoblacion != null && strPoblacion.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoblacion, 50, posicionY - 35, 0);
}
posicionY = posicionY - 80;
}
else {
posicionY = 670;
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Paciente:", 50, posicionY, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 5);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strNomPaciente, 50, posicionY - 20, 0);
}
if (strPoliza != null && strPoliza.length() > 0) {
pos = ajustarTextoADerecha(strPoliza, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoliza, pos, posicionY - 20, 0);
}
if (strAutorizacion != null && strAutorizacion.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "Num. Solicitud: " + strAutorizacion, 50, posicionY - 35, 0);
}
if (strPoblacion != null && strPoblacion.length() > 0) {
pos = ajustarTextoADerecha(strPoblacion, 540);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strPoblacion, pos, posicionY - 35, 0);
}
posicionY = posicionY - 80;
}
//AÑADIR ANALISIS/RECETAS/
switch(tipoDoc){
case OPC_PAC_PRESCRIPCION_DIAGNOSTICO:
{
strTexto = "Ruego faciliten las siguientes pruebas:";
break;
}
case OPC_PAC_PRESCRIPCION_ANALITICA:
{
strTexto = "Ruego faciliten los siguientes análisis:";
break;
}
case OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA:
{
strTexto = "Ruego faciliten las siguientes pruebas:";
break;
}
case OPC_PAC_PRESCRIPCION_FACTURACION:
{
strTexto = "Asistencia prestada:";
break;
}
case OPC_PAC_PETICION_AUTORIZACION:
{
strTexto = "Ruego faciliten la autorización de las siguientes pruebas:";
break;
}
case OPC_PAC_PRESCRIPCION_ATS:
{
strTexto = "Ruego realicen los siguientes actos:";
break;
}
case OPC_PAC_PRESCRIPCION_ESPECIALIDADES:
{
strTexto = "Ruego autoricen la asistencia a la especialidad:";
break;
}
case OPC_PAC_PRESCRIPCION_RECETAS:
{
strTexto = "DP./";
break;
}
case OPC_PAC_VOLANTE_INGRESO:
{
strTexto = "Solicito el siguiente ingreso:";
break;
}
}
int pagina = 1;
int posArray = 0;
if(tipoDoc != OPC_PAC_VOLANTE_INGRESO){
//IMPRIMIR ANALISIS
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strTexto, 50, posicionY, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 5);
//Bucle Determinaciones
String determinacion = "";
int contPag = 0;
int x = 0;
int x2 = 0;
int CaracLinea = 86; // número de caracteres por linea
for (int i=0;i<arrayListaElementosPrescripcion.size();i++) {
if (arrayListaElementosPrescripcion.get(i) != null) {
determinacion = (String)arrayListaElementosPrescripcion.get(i);
}
if (determinacion.length() > 0) {
//cb.showTextAligned(PdfContentByte.ALIGN_LEFT, determinacion.replaceAll(" ", ""), 50, posicionY -20 - x, 0);
determinacion = determinacion.replaceAll(" ", "");
String strLinea="";
int intLinea = (determinacion.length()/CaracLinea) + 1;
if (determinacion.length() <= CaracLinea){ // Controlar salto de linea
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, determinacion, 50, posicionY -20 - x, 0);
}else{
for (int s=0; s < intLinea; s ++){
if(determinacion.length() <= CaracLinea){
strLinea = determinacion;
}else{
strLinea = determinacion.substring(0, CaracLinea);
determinacion = determinacion.substring(CaracLinea);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, posicionY -20 - x, 0);
x += 10;
}
posicionY = posicionY - x;
}
}
x+=15;
if (x >= (35*15)){ //SI HAY MAS DE 35 ELEMENTOS SE CAMBIA DE PÁGINA
posArray = i+1;
pagina = 2;
i = arrayListaElementosPrescripcion.size(); //Salimos del FOR para pasar a la siguiente página
}
}
posicionY = posicionY - 20 - x;
if (pagina == 2){ // SEGUNDA PÁGINA PDF
cb.endText();
document.newPage();
//Nuevo cb para la segunda página
PdfContentByte cb2 = writer.getDirectContent();
cb.stroke();
BaseFont bf2 = BaseFont.createFont();
bf2 = BaseFont.createFont(bf2.TIMES_ROMAN, "", false);
cb2.beginText();
cb2.setFontAndSize(bf, 10);
x=0;
for (int i=posArray;i<arrayListaElementosPrescripcion.size();i++) {
if (arrayListaElementosPrescripcion.get(i) != null) {
determinacion = (String)arrayListaElementosPrescripcion.get(i);
}
if (determinacion.length() > 0) {
//cb2.showTextAligned(PdfContentByte.ALIGN_LEFT, determinacion.replaceAll(" ", ""), 50, 800 - x, 0);
determinacion = determinacion.replaceAll(" ", "");
String strLinea="";
int intLinea = (determinacion.length()/CaracLinea) + 1;
if (determinacion.length() <= CaracLinea){ // Controlar salto de linea
cb2.showTextAligned(PdfContentByte.ALIGN_LEFT, determinacion, 50, 800 - x, 0);
}else{
for (int s=0; s < intLinea; s ++){
if(determinacion.length() <= CaracLinea){
strLinea = determinacion;
}else{
strLinea = determinacion.substring(0, CaracLinea);
determinacion = determinacion.substring(CaracLinea);
}
cb2.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, 800 - x, 0);
x += 10;
}
posicionY = posicionY - x;
}
}
x+=15;
}
posicionY = 800 - x;
cb2.endText();
}
}
if (pagina==2){
cb.beginText();
}
if(tipoDoc == OPC_PAC_VOLANTE_INGRESO)
{
String strInformeCabecera = "Detalles del ingreso";
PersistenciaTtactmed perta = new PersistenciaTtactmed();
String detalle = "Motivo: "+ perta.obtenerDescripcionMotivoIngreso(Integer.parseInt(request.getParameter("motivo_ingreso")))+", acto a realizar: "+perta.obtenerNombreActo(Integer.parseInt(request.getParameter("acto_medico")), ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad());
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInformeCabecera, 50, posicionY - 20, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 25);
posicionY = posicionY - 40;
int CaracLinea = 86; // número de caracteres por linea
if (strInforme != null && strInforme.length() > 0) {
//cb.showTextAligned(PdfContentByte.ALIGN_LEFT, detalle, 50, posicionY - 40, 0);
String strLinea="";
int intLinea = (strInforme.length()/CaracLinea) + 1;
if (strInforme.length() <= CaracLinea){ // Controlar salto de linea
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInforme, 50, posicionY, 0);
}else{
int x = 0;
for (int i=0; i < intLinea; i ++){
if(strInforme.length() <= CaracLinea){
strLinea = strInforme;
}else{
strLinea = strInforme.substring(0, CaracLinea);
strInforme = strInforme.substring(CaracLinea);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, posicionY - x, 0);
x += 10;
}
posicionY = posicionY - x;
}
}
strTexto = "Informe médico";
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strTexto, 50, posicionY - 20, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 55);
if (strInforme != null && strInforme.length() > 0) {
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInforme, 50, posicionY - 40, 0);
}
}
else if (tipoDoc != OPC_PAC_PRESCRIPCION_FACTURACION && tipoDoc != OPC_PAC_PRESCRIPCION_RECETAS) {
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
strTexto = "Informe médico";
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strTexto, 50, posicionY - 20, 0);
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
ls.drawLine(cb, 50, 540, posicionY - 25);
int CaracLinea = 86; // número de caracteres por linea
if (strInforme != null && strInforme.length() > 0) {
posicionY = posicionY - 40;
//cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInforme, 50, posicionY - 40, 0);
String strLinea="";
int intLinea = (strInforme.length()/CaracLinea) + 1;
if (strInforme.length() <= CaracLinea){ // Controlar salto de linea
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInforme, 50, posicionY, 0);
}else{
int x = 0;
for (int i=0; i < intLinea; i ++){
if(strInforme.length() <= CaracLinea){
strLinea = strInforme;
}else{
strLinea = strInforme.substring(0, CaracLinea);
strInforme = strInforme.substring(CaracLinea);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, posicionY - x, 0);
x += 10;
}
}
}
}
//AÑADIR INFORME
if (tipoDoc == OPC_PAC_PRESCRIPCION_RECETAS) {
bf = BaseFont.createFont(bf.TIMES_BOLD, "", false);
cb.setFontAndSize(bf, 12);
strTexto = "Informe/Posología";
bf = BaseFont.createFont(bf.TIMES_ROMAN, "", false);
cb.setFontAndSize(bf, 10);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strTexto, 50, posicionY - 20, 0);
ls.drawLine(cb, 50, 540, posicionY - 25);
int CaracLinea = 86; // número de caracteres por linea
if (strInforme != null && strInforme.length() > 0) {
posicionY = posicionY - 40;
//cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInforme, 50, posicionY - 40, 0);
String strLinea="";
int intLinea = (strInforme.length()/CaracLinea) + 1;
if (strInforme.length() <= CaracLinea){ // Controlar salto de linea
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strInforme, 50, posicionY, 0);
}else{
int x = 0;
for (int i=0; i < intLinea; i ++){
if(strInforme.length() <= CaracLinea){
strLinea = strInforme;
}else{
strLinea = strInforme.substring(0, CaracLinea);
strInforme = strInforme.substring(CaracLinea);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, posicionY - x, 0);
x += 10;
}
}
}
}
cb.endText();
//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());
}
}
/**
* Evalúa la opción del módulo de gestión de pacientes 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 request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private void evaluarOpcion(String sOpcion, HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws IOException
{
int nOpcion = 0;
try
{
nOpcion = Integer.parseInt(sOpcion);
}
catch(NumberFormatException e)
{
LogTarisan.logger.log(NivelLog.INFO, "Excepción: " + e);
}
switch(nOpcion)
{
case OPC_PAC_VER_PDF:
{
String nombrePDF = "";
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();
DES encrypter = new DES(strMedico);
nombrePDF = request.getParameter("nombrePDF");
if (nombrePDF.contains(" ")){
nombrePDF = nombrePDF.replaceAll(" ", "+");
}
nombrePDF = encrypter.decrypt(nombrePDF);
nombrePDF = nombrePDF + ".pdf";
int tipo = 0;
tipo = Integer.parseInt(request.getParameter("tipo"));
String rutaPDF = "";
switch (tipo){
case 1: rutaPDF = ParametrosConfiguracion.ruta_pdf_resultados_analiticas + nombrePDF;
break;
case 2: rutaPDF = ParametrosConfiguracion.ruta_pdf_resultados_anatomia + nombrePDF;
break;
case 3: rutaPDF = ParametrosConfiguracion.ruta_pdf_informes_rx + nombrePDF;
break;
case 4: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_analiticas + nombrePDF;
break;
case 5: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_analiticas_capturadas + nombrePDF;
break;
case 6: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_ap + nombrePDF;
break;
case 7: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_ats + nombrePDF;
break;
case 8: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_autorizaciones + nombrePDF;
break;
case 9: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_detalle_pacientes + nombrePDF;
break;
case 10: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_especialidades + nombrePDF;
break;
case 11: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_facturas + nombrePDF;
break;
case 12: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_ingresos + nombrePDF;
break;
case 13: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_recetas + nombrePDF;
break;
case 14: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_rx + nombrePDF;
break;
case 15: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones + nombrePDF;
break;
case 16: rutaPDF = ParametrosConfiguracion.ruta_pdf_resultados + nombrePDF;
break;
case 17: rutaPDF = ParametrosConfiguracion.ruta_pdf_liquidaciones + nombrePDF;
break;
case 18: rutaPDF = ParametrosConfiguracion.ruta_pdf_peticiones_rx_capturados + nombrePDF;
break;
case 19: rutaPDF = ParametrosConfiguracion.ruta_pdf_irpf + nombrePDF;
break;
case 20: rutaPDF = ParametrosConfiguracion.ruta_pdf_franquicias + nombrePDF;
break;
case 21: rutaPDF = ParametrosConfiguracion.ruta_pdf_resultados_anatomia_CSM + nombrePDF;
break;
}
File file = new File(rutaPDF);
response.setHeader("Content-Type", getServletContext().getMimeType(file.getName()));
response.setHeader("Content-Length", String.valueOf(file.length()));
response.setHeader("Content-Disposition", "inline; filename=\"" + nombrePDF + "\"");
Files.copy(file.toPath(), response.getOutputStream());
break;
}
case OPC_PAC_GESTOR:
{
sesion.setAttribute("PACIENTE", null);
LogTarisan.logger.log(NivelLog.DEBUG, "Limpiamos el paciente: "+sesion.getAttribute("PACIENTE"));
response.sendRedirect("../jsp/pac/gestor.jsp");
break;
}
case OPC_PAC_FACTURACION:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Facturación' seleccionada");
response.sendRedirect("../jsp/pac/facturacion.jsp?x=0&pagina=1");
break;
}
case OPC_PAC_FACTURACION_ODON:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Facturación' seleccionada");
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
break;
}
case OPC_PAC_FACTURACION_ESTOMATOLOGIA:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Facturación' seleccionada");
response.sendRedirect("../jsp/pac/estomatologia.jsp?x=2&pagina=1");
break;
}
case OPC_PAC_AUTORIZACION:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Autorizacion' seleccionada");
response.sendRedirect("../jsp/pac/autorizacion.jsp?x=3");
break;
}
case OPC_PAC_ANALITICA:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Analítica' seleccionada");
response.sendRedirect("../jsp/pac/analitica.jsp?x=4");
break;
}
case OPC_PAC_DIAGNOSTICO:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Diagnostico' seleccionada");
response.sendRedirect("../jsp/pac/diagnostico.jsp?x=5");
break;
}
case OPC_PAC_ESPECIALIDADES:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Otras Especialidades' seleccionada");
response.sendRedirect("../jsp/pac/especialidades.jsp?x=6");
break;
}
case OPC_PAC_RECETAS:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Recetas' seleccionada");
response.sendRedirect("../jsp/pac/recetas.jsp?x=7");
break;
}
case OPC_PAC_HISTORIA:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Historia de Pacientes' seleccionada");
response.sendRedirect("../jsp/pac/historia.jsp?x=8");
break;
}
case OPC_PAC_ANALISTA:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Analista' seleccionada");
response.sendRedirect("../jsp/pac/analista.jsp?x=10");
break;
}
case OPC_PAC_RADIOLOGO:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Opción 'Radiologo' seleccionada");
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11");
break;
}
case OPC_PAC_PASO_TARJETA:
{
try
{
if (sesion.getAttribute("PACIENTE") != null)
{
sesion.removeAttribute("PACIENTE");
}
LogTarisan.logger.log(NivelLog.DEBUG, "Paso de Tarjeta del Paciente");
this.validarTarjeta(request, response, sesion);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PASO_TARJETA: " + ex.getMensaje());
if (ex.getMensaje()!=null){
sesion.setAttribute("ERROR", ex.getMensaje());
}else{
sesion.setAttribute("ERROR", "Tarjeta inválida");
}
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PASO_TARJETA: " + ex);
sesion.setAttribute("ERROR", "Tarjeta inválida");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_LEER_NUMERO_TARJETA_ATS:
{
try
{
if (sesion.getAttribute("PACIENTE") != null)
{
sesion.removeAttribute("PACIENTE");
}
LogTarisan.logger.log(NivelLog.DEBUG, "Leer el número de la tarjeta del paciente. Para ATS: " + (String)sesion.getAttribute("PERFIL"));
this.validarTarjeta(request, response, sesion);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - : OPC_PAC_LEER_NUMERO_TARJETA_ATS" + ex.getMensaje());
sesion.setAttribute("ERROR", "Tarjeta inválida");
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_LEER_NUMERO_TARJETA_ATS: " + ex);
sesion.setAttribute("ERROR", "Tarjeta inválida");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_ACTUALIZAR_HISTORIA_PACIENTE:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se actualiza el historial del paciente");
this.actualizarHistoriaPaciente(request, response, sesion);
response.sendRedirect("../jsp/pac/historia.jsp?x=" + request.getParameter("x") + "&pagina=1");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan - OPC_PAC_ACTUALIZAR_HISTORIA_PACIENTE: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la actualizacion del historial del paciente." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_ACTUALIZAR_HISTORIA_PACIENTE: " + ex);
sesion.setAttribute("ERROR", "Error en la actualizacion del historial del paciente.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_ESPECIALIDADES:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se graba la prescripcion de otras especialidades");
this.prescripcionEspecialidades(request, response, sesion);
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_ESPECIALIDADES);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String auto = (String)request.getAttribute("autorizacion");
String autoEncriptada = encrypter.encrypt(auto);
request.setAttribute("autorizacion", autoEncriptada);
request.getRequestDispatcher("/jsp/pac/peticiones.jsp").forward(request, response);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_ESPECIALIDADES: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la prescripción de otras especialidades." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PRESCRIPCION_ESPECIALIDADES: " + ex);
sesion.setAttribute("ERROR", "Error en la prescripción de otras especialidades.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_DIAGNOSTICO:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se graba la prescripcion de los radiodiagnosticos");
//this.prescripcionRadiodiagnosticos(request, response, sesion);
boolean justificacionNiveles=false;
/*if (request.getParameter("justificacionNiveles").equalsIgnoreCase("false")){
justificacionNiveles= false;
}else{
justificacionNiveles= true;
}*/
this.prescripcionDiagnosticos(request, response, sesion, justificacionNiveles);
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_DIAGNOSTICO);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String auto = (String)request.getAttribute("autorizacion");
String autoEncriptada = encrypter.encrypt(auto);
request.setAttribute("autorizacion", autoEncriptada);
request.getRequestDispatcher("/jsp/pac/diagnostico.jsp").forward(request, response);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_DIAGNOSTICO: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la prescripción de los radiodiagnosticos." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PRESCRIPCION_DIAGNOSTICO: " + ex);
sesion.setAttribute("ERROR", "Error en la prescripción de los radiodiagnosticos.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_ANALITICA:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se graba la prescripcion de la analitica. Para el paciente:"+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadIMQ()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario());
LogTarisan.logger.log(NivelLog.DEBUG, "Se van a insertar los siguientes codigos de analitica: "+(String)request.getParameter("listaCodigoElementosPrescripcion"));
if(this.prescripcionAnaliticas(request, response, sesion))
{
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_ANALITICA);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String auto = (String)request.getAttribute("autorizacion");
String autoEncriptada = encrypter.encrypt(auto);
request.setAttribute("autorizacion", autoEncriptada);
request.getRequestDispatcher("../jsp/pac/analitica.jsp?x=4&pagina=1").forward(request,response);
}
else
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_ANALITICA ");
sesion.setAttribute("ERROR", "Error en la prescripción de la analitica.");
response.sendRedirect("../jsp/error.jsp");
}
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_ANALITICA: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la prescripción de la analitica." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PRESCRIPCION_ANALITICA: " + ex);
ex.printStackTrace();
sesion.setAttribute("ERROR", "Error en la prescripción de la analitica.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se graba la prescripcion de la anatomia patologica. Para el paciente:"+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadIMQ()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario());
LogTarisan.logger.log(NivelLog.DEBUG, "Se van a insertar los siguientes codigos de anatomia patologica: "+(String)request.getParameter("listaCodigoElementosPrescripcion"));
if(this.prescripcionAnaliticas(request, response, sesion))
{
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();
DES encrypter = new DES(strMedico);
String auto = ""+request.getAttribute("autorizacion");
String autoEncriptada = encrypter.encrypt(auto);
request.setAttribute("autorizacion", autoEncriptada);
request.getRequestDispatcher("../jsp/pac/anatomia.jsp?x=6&pagina=1").forward(request,response);
// response.sendRedirect("../jsp/pac/anatomia.jsp?x=6&pagina=1");
}
else
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA ");
sesion.setAttribute("ERROR", "Error en la prescripción de anatomia patologica.");
response.sendRedirect("../jsp/error.jsp");
}
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la prescripción de anatomia patologica." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA: " + ex);
ex.printStackTrace();
sesion.setAttribute("ERROR", "Error en la prescripción de anatomia patologica.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_RECETAS:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Prescripción de receta");
this.generarPDFRecetas(request, response, sesion, OPC_PAC_PRESCRIPCION_RECETAS);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String recetaEncriptada = encrypter.encrypt(strMedico);
sesion.setAttribute("receta", recetaEncriptada);
response.sendRedirect("../jsp/pac/recetas.jsp?x=8&pagina=1&imp=1");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_RECETAS: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la prescripción de la analitica." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PRESCRIPCION_RECETAS: " + ex);
sesion.setAttribute("ERROR", "Error en la prescripción de la analitica.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_MED_DETALLE_PACIENTE:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Detalle paciente OPC_MED_DETALLE_PACIENTE");
LogTarisan.logger.log(NivelLog.DEBUG, "Llamamos al generarPDFDetalle");
//this.generarPDFDetalle(request, response, sesion);
this.generarPDFDetalleFechas(request, response, sesion);
LogTarisan.logger.log(NivelLog.DEBUG, "Hemos llamado a generarPDFDetalle");
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String detalleEncriptado = encrypter.encrypt(strMedico);
sesion.setAttribute("ENC", detalleEncriptado);
response.sendRedirect("../jsp/med/detallePacientes.jsp?x=6&pagina=1&imp=1");
} catch (Exception ex) {
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_MED_DETALLE_PACIENTE: " + ex);
sesion.setAttribute("ERROR", "Error al actualizar la tabla TAREGLOG.");
response.sendRedirect("../jsp/error.jsp");
} catch (ExcepcionTarisan e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
/*case OPC_PAC_DETALLE_PACIENTE:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Detalle paciente OPC_PAC_DETALLE_PACIENTE");
LogTarisan.logger.log(NivelLog.DEBUG, "Llamamos al generarPDFDetalle");
this.generarPDFDetalle(request, response, sesion);
LogTarisan.logger.log(NivelLog.DEBUG, "Hemos llamado a generarPDFDetalle");
response.sendRedirect("../jsp/pac/detallePacientes.jsp?x=14&pagina=1&imp=1");
//request.getRequestDispatcher("/jsp/med/detallePacientes.jsp").forward(request,response);
} catch (Exception ex) {
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_DETALLE_PACIENTE: " + ex);
sesion.setAttribute("ERROR", "Error al actualizar la tabla TAREGLOG.");
response.sendRedirect("../jsp/error.jsp");
} catch (ExcepcionTarisan e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}*/
case OPC_PAC_PRESCRIPCION_FACTURACION:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se efectua la facturacion de actos medicos prescribibles");
if(this.facturacionActosPrescribibles(request, response, sesion))
{
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_FACTURACION);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String facturacionEncriptada = encrypter.encrypt(((Usuario)sesion.getAttribute("USUARIO")).getMedico()+"_"+((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza());
sesion.setAttribute("ENC", facturacionEncriptada);
request.getRequestDispatcher("/jsp/pac/facturacion.jsp").forward(request, response);
}
else
response.sendRedirect("../jsp/error.jsp");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PRESCRIPCION_FACTURACION: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PRESCRIPCION_FACTURACION: " + ex);
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_FACTURACION_ODON:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se efectua la facturacion de actos medicos prescribibles de odontologia");
if(this.facturacionActosPrescribibles(request, response, sesion))
{
this.facturacionActosPrescribiblesEstomatologia(request, response, sesion);
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_FACTURACION);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String facturacionEncriptada = encrypter.encrypt(((Usuario)sesion.getAttribute("USUARIO")).getMedico()+"_"+((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza());
sesion.setAttribute("ENC", facturacionEncriptada);
request.getRequestDispatcher("/jsp/pac/facturacion_odon.jsp").forward(request, response);
//response.sendRedirect("/tarisan/jsp/pac/facturacion_odon.jsp");
}
else
response.sendRedirect("../jsp/error.jsp");
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_FACTURACION_ODON: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles de odontologia." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_FACTURACION_ODON: " + ex);
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles de odontologia.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_FACTURACION_REHABPOD:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se efectua la facturacion de actos medicos rehabilitacion / podología: "+request);
//boolean pulsado = (boolean) sesion.getAttribute("pulsadok");
//if (pulsado){
if(this.facturacionSesionRehabPod(request, response, sesion)){
request.getRequestDispatcher("/jsp/pac/facturacion_rehabpod.jsp").forward(request, response);
//sesion.setAttribute("pulsadok", false);
}else
response.sendRedirect("../jsp/error.jsp");
/*}else{
request.getRequestDispatcher("/jsp/pac/facturacion_rehabpod.jsp").forward(request, response);
sesion.setAttribute("pulsadok", false);
}*/
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_FACTURACION_REHABPOD: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_FACTURACION_REHABPOD: " + ex);
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_FACTURACION_CHIPCARD:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se efectua la facturacion de actos medicos para asegurados desplazados");
this.facturacionChipcard(request, response, sesion);
request.getRequestDispatcher("/jsp/pac/facturacion_chipcard.jsp").forward(request, response);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_FACTURACION_CHIPCARD: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_FACTURACION_CHIPCARD: " + ex);
sesion.setAttribute("ERROR", "Error en la facturacion de actos medicos prescribibles.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PETICION_AUTORIZACION:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se graba la peticion de autorizacion");
this.peticionAutorizacion(request, response, sesion);
this.generarPDF(request, response, sesion, OPC_PAC_PETICION_AUTORIZACION);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();;
DES encrypter = new DES(strMedico);
String auto = (String)request.getAttribute("autorizacion");
String autoEncriptada = encrypter.encrypt(auto);
request.setAttribute("autorizacion", autoEncriptada);
request.getRequestDispatcher("/jsp/pac/autorizaciones.jsp").forward(request, response);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_PETICION_AUTORIZACION: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la peticion de autorizacion." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_PETICION_AUTORIZACION: " + ex);
sesion.setAttribute("ERROR", "Error en la peticion de autorizacion.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_VOLANTE_INGRESO:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a insertar la autorización de ingreso: "+request.getParameterNames().toString());
try {
if(this.insertarVolanteIngreso(request, response, sesion))
{
this.generarPDF(request, response, sesion, OPC_PAC_VOLANTE_INGRESO);
request.getRequestDispatcher("/jsp/pac/volante_medico.jsp?x=12&imp=1").forward(request, response);
}
else
{
sesion.setAttribute("ERROR", "Error en la generacion del volante de ingreso. ");
response.sendRedirect("../jsp/error.jsp");
}
} catch (ExcepcionTarisan e) {
sesion.setAttribute("ERROR", "Error en la generacion del volante de ingreso. "+e.toString());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
sesion.setAttribute("ERROR", "Error en la generacion del volante de ingreso. "+ex.toString());
response.sendRedirect("../jsp/error.jsp");
}
//response.sendRedirect("../jsp/pac/volante_medico.jsp?x=12");
break;
}
case OPC_PAC_IMPRIMIR_VOLANTE_INGRESO:
{
try {
this.generarPDF(request, response, sesion, OPC_PAC_VOLANTE_INGRESO);
//request.getRequestDispatcher("/jsp/med/historico_volantes.jsp?x=14&imp=1").forward(request, response);
response.sendRedirect("../jsp/med/historico_volantes.jsp?x=14&imp=1");
}
catch (ExcepcionTarisan e) {
sesion.setAttribute("ERROR", "Error en la impresion del volante de ingreso. "+e.toString());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
sesion.setAttribute("ERROR", "Error en la impresion del volante de ingreso. "+ex.toString());
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_BORRAR_VOLANTE_INGRESO:
{
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a -borrar- el volante de ingreso: "+request.getParameter("pk"));
try {
PersistenciaTavolin perta = new PersistenciaTavolin();
if(perta.marcar_volante_erroneo(Integer.parseInt(request.getParameter("pk"))))
response.sendRedirect("../jsp/med/historico_volantes.jsp?x=14");
else
{
sesion.setAttribute("ERROR", "Error en el -borrado- del volante de ingreso. "+request.getParameter("pk"));
response.sendRedirect("../jsp/error.jsp");
}
}
catch(Exception ex)
{
sesion.setAttribute("ERROR", "Error en el -borrado- del volante de ingreso. "+ex.toString());
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_ANALISTA_ACEPTAR_ANALISIS:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se acepta el analisis prescrito");
int resp = this.aceptarAnalisisPrescrito(request, response, sesion);
response.sendRedirect("../jsp/pac/analista.jsp?x=10&respuesta=" + resp);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_ANALISTA_ACEPTAR_ANALISIS: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error al aceptar el analisis prescrito." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_ANALISTA_ACEPTAR_ANALISIS: " + ex);
sesion.setAttribute("ERROR", "Error al aceptar el analisis prescrito.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_ANALISTA_ACEPTAR_RADIODIAGNOSTICO:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se acepta el radiodiagnóstico prescrito");
int resp = this.aceptarAnalisisPrescrito(request, response, sesion);
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&respuesta=" + resp);
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_ANALISTA_ACEPTAR_RADIODIAGNOSTICO: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error al aceptar el radiodiagnóstico prescrito." + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_ANALISTA_ACEPTAR_RADIODIAGNOSTICO: " + ex);
sesion.setAttribute("ERROR", "Error al aceptar el radiodiagnóstico prescrito.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_FIRMA_BENEFICIARIO:
{
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "El beneficiario firma la solicitud de autorización");
PersistenciaPaciente per = new PersistenciaPaciente();
per.firmarAutorizacion(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
//se trata de un analista. se le redirecciona a la pagina de analista
if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA) ) {
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
//se trata de un radiologo. se le redirecciona a la pagina de radiologo.jsp
}else if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO) ) {
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
//se trata de un especialista o de un medico de cabecera. Se le redirecciona a la pagina de facturacion.
}else{
response.sendRedirect("../jsp/pac/facturacion.jsp?x=0&pagina=1");
}
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion Tarisan - OPC_PAC_FIRMA_BENEFICIARIO: " + ex.getMensaje());
sesion.setAttribute("ERROR", "Error en la firma de autorización del beneficiario" + ex.getMensaje());
response.sendRedirect("../jsp/error.jsp");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - OPC_PAC_FIRMA_BENEFICIARIO: " + ex);
sesion.setAttribute("ERROR", "Error en la firma de autorización del beneficiario");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
case OPC_PAC_PRESCRIPCION_ATS:
{
LogTarisan.logger.log(NivelLog.INFO, "Vamos a grabar la prescripcion del medico para el ATS en taconaut");
try {
if(this.insertarPrescripcionAutorizacion(request, response, sesion))
{
this.generarPDF(request, response, sesion, OPC_PAC_PRESCRIPCION_ATS);
//Pasamos la autorizacion encriptada para la impresión
String strMedico = ""+((Usuario)sesion.getAttribute("USUARIO")).getMedico();
DES encrypter = new DES(strMedico);
String auto = ""+request.getAttribute("autorizacion");
String autoEncriptada = encrypter.encrypt(auto);
request.setAttribute("autorizacion", autoEncriptada);
LogTarisan.logger.log(NivelLog.INFO, strMedico + " - Se insertó correctamente la prescripcion del ATS ");
sesion.setAttribute("DEBUG", strMedico + " - Autorizaci&oacute;n insertada correctamente");
request.getRequestDispatcher("/jsp/pac/ats.jsp?x=13&imp=1&pagina=1").forward(request, response);
}
else
{
LogTarisan.logger.log(NivelLog.ERROR, "Error en la opcion - OPC_PAC_PRESCRIPCION_ATS ");
sesion.setAttribute("ERROR", "Error en la prescripcion para los ATS");
response.sendRedirect("../jsp/error.jsp");
}
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "Error en la opcion - OPC_PAC_PRESCRIPCION_ATS - Excepcion tarisan: " + e.toString());
sesion.setAttribute("ERROR", "Error en la prescripcion para los ATS");
response.sendRedirect("../jsp/error.jsp");
} catch (ServletException e) {
LogTarisan.logger.log(NivelLog.ERROR, "Error en la opcion - OPC_PAC_PRESCRIPCION_ATS - ServletException: " + e.toString());
sesion.setAttribute("ERROR", "Error en la prescripcion para los ATS");
response.sendRedirect("../jsp/error.jsp");
}
LogTarisan.logger.log(NivelLog.INFO, "Fin OPC_PAC_PRESCRIPCION_ATS");
break;
}
case OPC_PAC_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, "Excepcion Tarisan - OPC_PAC_REGISTRAR_LOG_ANALISIS: " + 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, "Excepcion - OPC_PAC_REGISTRAR_LOG_ANALISIS: " + ex);
sesion.setAttribute("ERROR", "Error al actualizar la tabla TAREGLOG.");
response.sendRedirect("../jsp/error.jsp");
}
break;
}
default:
{
response.sendRedirect("../jsp/pac/gestor.jsp");
break;
}
}
}
/**
* Calcula el siguiente código de autorización utilizando el código del médico y el valor del campo param1.
* @param medico Código del médico.
* @param param1 Valor del campo param1 del médico.
* @return El valor del siguiente código de autorización.
*/
private long calcularCodigoAutorizacion(int medico, int param1) throws ExcepcionTarisan
{
try
{
//creamos el valor de param1. Debe ser un valor de 5 digitos.
String strParam1 = Integer.toString(param1);
for (int indice=strParam1.length();indice<5;indice++)
strParam1 = "0" + strParam1;
//calculamos el numero de autorizacion para la prescripcion a realizar
//calculo del numero de autorizacion: 3 últimos dígitos del código del médico> + <PARAM1+ 1>
String strMedico = String.valueOf(medico);
//strMedico = strMedico.substring(0,strMedico.length());
/*int tamano = 0;
if (strMedico.length() >= 3)
tamano = 3;
else tamano = strMedico.length();
strMedico = strMedico.substring(0,tamano);
*/
long longAutorizacion = Long.parseLong(strMedico + strParam1) + 1;
LogTarisan.logger.log(NivelLog.DEBUG, "Termina CalcularCodigoAutorizacion: "+longAutorizacion);
return longAutorizacion;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion - calcularCodigoAutorizacion: " + ex);
throw new ExcepcionTarisan(ex.getMessage());
}
}
private void facturacionChipcard (HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
int contrato = 0;
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
int intUltimoValorCorrelativo = perTareglog.obtenerUltimoValorCorrelativo(intMedico, tsFechaUltimoAcceso);
int intEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
PersistenciaTamovext perTamovext = new PersistenciaTamovext();
/*int intUltimoValorNumSeq = perTamovext.obtenerUltimoValorNumSeq(intMedico);*/
String strCodigoActos = (String)request.getParameter("listaCodigoElementosPrescripcion");
String limpio = strCodigoActos.replaceAll("Â", "");
strCodigoActos = limpio;
StringTokenizer st = new StringTokenizer(limpio, "¬");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
PersistenciaTtactmed perttactmed = new PersistenciaTtactmed();
int intTarifa = ((Usuario)sesion.getAttribute("USUARIO")).getTarifa();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
Tamensaje tamensaje = new Tamensaje();
PersistenciaTamensaje pertamensaje = new PersistenciaTamensaje();
tamensaje = pertamensaje.obtenerMensaje(2);
Tarjeta tar = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta();
contrato = tar.getContrato();
String tarjetaDesplazado = tar.getTarjetaDesplazado();
//((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado();
while (st.hasMoreTokens())
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se procesan los actos "+strCodigoActos);
//obtenemos los valores especificos para cada acto medico
String token = st.nextToken();
if(token.length()>0)
{
int acto = Integer.parseInt(token);
//LogTarisan.logger.log(NivelLog.DEBUG, "acto: "+acto);
int actoChipcard = acto;
PersistenciaTamovext perTamovex = new PersistenciaTamovext();
if(perTamovex.esPrimeraVisitaDesplazado(intMedico, tarjetaDesplazado, true))
{
if(acto == 2 && !perTamovext.tieneConsultaChipcard(intMedico, tarjetaDesplazado))
actoChipcard = 1;
if(acto == 1 && perTamovext.tieneConsultaChipcard(intMedico, tarjetaDesplazado))
actoChipcard = 2;
}
Object [] aValores = new Object[15];
aValores[0] = Integer.valueOf(intMedico);//MEDICO
aValores[1] = Integer.valueOf(intEspecialidad); //ESPECIALIDAD
aValores[2] = Integer.valueOf(acto);//ACTO
/*cambiamos el numseq a tipo autoincrement de oracle*/
//aValores[3] = Integer.valueOf(intUltimoValorNumSeq + 1);//NUMSEQ
/*
* Buscamos Por la tarjeta chipcard en ttbenefi - ttiguala
* para conseguir colectivo poliza orden...
*/
aValores[3] = Long.valueOf(tar.getColectivo());//colec
aValores[4] = Double.valueOf(tar.getPoliza());//pol
aValores[5] = Integer.valueOf(tar.getBeneficiario());//orden
LogTarisan.logger.log(NivelLog.DEBUG, "El paciente en sesion tiene, contrato = "+tar.getContrato()+", colectivo = "+tar.getColectivo()+", poliza = "+tar.getPoliza()+", orden = "+tar.getBeneficiario()+", entidad= "+tar.getEntidadIMQ()+", entidadChipcard = "+tar.getEntidadChipcard());
aValores[6] = dtFecha;//FECHA
aValores[7] = Double.valueOf(perttactmed.obtenerPrecioActoMedico(intTarifa, acto, intEspecialidad));//PRECIO
aValores[8] = Integer.valueOf(intMedico);//PRESCRIPTOR
aValores[9] = new String(tarjetaDesplazado);//TARJETA_CHIPCARD
aValores[10] = Integer.valueOf(intEspecialidad);//ESPECIALIDAD_CHIPCARD
aValores[11] = Integer.valueOf(actoChipcard);//ACTO_CHIPCARD
aValores[12] = Integer.valueOf(0);//talon_chipcard
aValores[13] = Integer.valueOf(tar.getEntidadIMQ());
aValores[14] = Integer.valueOf(0); //autorizacion IMQ
//intUltimoValorNumSeq++;
String entidadChipcard = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard();
int entidad=0;
if(tar.getEntidadIMQ() == 0)
{
if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
entidad=3;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_dkv) == 0)
entidad=32;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
entidad=5;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0)
entidad=3;
//entidad=7;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_redsa_asisa)==0)
entidad=4;
}
else {
entidad = tar.getEntidadIMQ();
}
//aValores[15] = Integer.valueOf(entidad);
tar.setEntidadIMQ(entidad);
//A partir de aquí hay que distinguir si es adeslas o no para que vaya a chipcard o no...
//
LogTarisan.logger.log(NivelLog.DEBUG, "entidad IMQ: "+aValores[13]);
RespuestaChipcard respuesta = new RespuestaChipcard();
boolean respuesta_correcta = false;
if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
{
PersistenciaRespuestaChipcard perRes = new PersistenciaRespuestaChipcard();
String sMensaje ="";
String talon_chipcard = "";
// try {
Calendar fecha_hora = Calendar.getInstance();
Integer secuencia = perRes.obtenerSecuencia();
boolean registro_peticion = perRes.insertar_peticiones(intMedico, intEspecialidad, actoChipcard, tar.getTarjetaDesplazado(), fecha_hora, secuencia);
//System.out.println("Se pide a chipcard. chipcard_login:" + ParametrosConfiguracion.chipcard_login + "; chipcard_pass: " + ParametrosConfiguracion.chipcard_pass + "chipcard_terminal: " + Integer.parseInt(ParametrosConfiguracion.chipcard_terminal) + " chipcard_company: " + Integer.parseInt(ParametrosConfiguracion.chipcard_company) + ", chipcard_url: " + ParametrosConfiguracion.chipcard_url + ", pista2: " + tar.getPista2() + "chipcard_profesional: " + ParametrosConfiguracion.chipcard_profesional + ", especialidad: " + intEspecialidad + ", chipcard_lista: " + Integer.parseInt(ParametrosConfiguracion.chipcard_lista) + ", actoChipcard:" + actoChipcard +"\n\n");
if(registro_peticion)
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha insertado bien la peticion de chipcard.");
else
LogTarisan.logger.log(NivelLog.ERROR, "No se ha insertado la peticion de chipcard");
// LogTarisan.logger.log(NivelLog.DEBUG, "Tarisan.check_card se llama con estos parametros --> chipcard_login:" + ParametrosConfiguracion.chipcard_login + "; chipcard_pass: " + ParametrosConfiguracion.chipcard_pass + "chipcard_terminal: " + Integer.parseInt(ParametrosConfiguracion.chipcard_terminal) + " chipcard_company: " + Integer.parseInt(ParametrosConfiguracion.chipcard_company) + ", chipcard_url: " + ParametrosConfiguracion.chipcard_url + ", pista2: " + tar.getPista2() + "chipcard_profesional: " + ParametrosConfiguracion.chipcard_profesional + ", especialidad: " + intEspecialidad + ", chipcard_lista: " + Integer.parseInt(ParametrosConfiguracion.chipcard_lista) + ", actoChipcard:" + actoChipcard +"\n\n");
//Para llamar a chipcard y que guarde los resultados en desa o en real comprobamos si el entorno de Tarisan es desa o real.
/*
String destino ="";
if(ParametrosConfiguracion.db_destino.contains("desa"))
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llamamos a chipcard en DESA");
destino = "DESA";
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llamamos a chipcard en REAL");
destino = "REAL";
}
OracleParametros oraParam = new OracleParametros();
destino = oraParam.cadenaConexion;*/
//Llamamos a tarisan.check_card que realiza la petición a chipcard e inserta en Alberto el resultado que nos devuelve chipcard
//Tarisan.check_card(ParametrosConfiguracion.chipcard_login, ParametrosConfiguracion.chipcard_pass, Integer.parseInt(ParametrosConfiguracion.chipcard_terminal), Integer.parseInt(ParametrosConfiguracion.chipcard_company), ParametrosConfiguracion.chipcard_url, tar.getPista2(), ParametrosConfiguracion.chipcard_profesional, intEspecialidad, Integer.parseInt(ParametrosConfiguracion.chipcard_lista), actoChipcard, secuencia.intValue(), destino);
Tarisan.check_card(ParametrosConfiguracion.chipcard_login, ParametrosConfiguracion.chipcard_pass, Integer.parseInt(ParametrosConfiguracion.chipcard_terminal), Integer.parseInt(ParametrosConfiguracion.chipcard_company), ParametrosConfiguracion.chipcard_url, tar.getPista2(), ParametrosConfiguracion.chipcard_profesional, intEspecialidad, Integer.parseInt(ParametrosConfiguracion.chipcard_lista), actoChipcard, secuencia.intValue());
int i = 0;
//hay veces que tarda en dar la respuesta, por lo que aquí le hago esperar un máximo de 5 segundos
while(!perRes.obtener_resultado_secuencia(secuencia) && i<5)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Esperando "+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
i+=1;
}
//si se da absoluta concurrencia hay veces que chipcard no devuelve el resultado de una petición, si llega a este punto y todavía no hay respuesta, vuelvo a llamar a chipcard a ver si consigo respuesta
if(!perRes.obtener_resultado_secuencia(secuencia))
{
//Tarisan.check_card(ParametrosConfiguracion.chipcard_login, ParametrosConfiguracion.chipcard_pass, Integer.parseInt(ParametrosConfiguracion.chipcard_terminal), Integer.parseInt(ParametrosConfiguracion.chipcard_company), ParametrosConfiguracion.chipcard_url, tar.getPista2(), ParametrosConfiguracion.chipcard_profesional, intEspecialidad, Integer.parseInt(ParametrosConfiguracion.chipcard_lista), actoChipcard, secuencia.intValue(), destino);
Tarisan.check_card(ParametrosConfiguracion.chipcard_login, ParametrosConfiguracion.chipcard_pass, Integer.parseInt(ParametrosConfiguracion.chipcard_terminal), Integer.parseInt(ParametrosConfiguracion.chipcard_company), ParametrosConfiguracion.chipcard_url, tar.getPista2(), ParametrosConfiguracion.chipcard_profesional, intEspecialidad, Integer.parseInt(ParametrosConfiguracion.chipcard_lista), actoChipcard, secuencia.intValue());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
talon_chipcard = perRes.obtener_respuesta_secuencia(secuencia);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nTarisan.check_card devuelve: talon_chipcard --> "+talon_chipcard+"\n\n");
if(talon_chipcard == null)
{
try {
Thread.sleep(1000);
talon_chipcard = perRes.obtener_respuesta_secuencia(secuencia);
} catch (InterruptedException e) {
}
}
respuesta = perRes.parsearRespuesta(talon_chipcard);
/*} catch (InterruptedException e) {
sMensaje = "La tarjeta de Adeslas Respuesta de chipcard Error";
LogTarisan.logger.log(NivelLog.DEBUG, "Error al hacer thread.sleep");
sesion.setAttribute("ERROR", sMensaje);*/
//}
//if(perRes.insertar_movimientos(respuesta, secuencia))
// LogTarisan.logger.log(NivelLog.DEBUG, "Se ha insertado correctamente el control de chipcard para la transaccion: "+respuesta.get_talon_chipcard());
//else
//LogTarisan.logger.log(NivelLog.DEBUG, "Error al insertar el movimiento de chipcard: "+respuesta.get_mensaje());
sMensaje = "\n\nLa tarjeta de Adeslas Respuesta de chipcard Error? "+respuesta.get_error()+": <br/>terminal: "+respuesta.get_terminal()+"<br/>respuesta: "+respuesta.get_respuesta() +"<br/>mensaje: "+ respuesta.get_mensaje() +"<br/>num_aut: "+respuesta.get_talon_chipcard()+"\n\n";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a comparar las tarjetas de desplazados de sesion y de respuesta chipcard. Respuesta: "+respuesta.get_tarjeta().substring(14)+", sesion: "+tar.getTarjetaDesplazado());
if(respuesta.get_tarjeta().substring(14).equals(tar.getTarjetaDesplazado()))
{
LogTarisan.logger.log(NivelLog.DEBUG, "Las tarjetas coinciden");
//respuesta_correcta = perRes.obtener_resultado_secuencia(secuencia);
}
else
{
LogTarisan.logger.log(NivelLog.ERROR, "Las tarjetas no coinciden");
//respuesta_correcta = perRes.obtener_resultado_secuencia(secuencia);
}
respuesta_correcta = respuesta.get_respuesta().contains(ParametrosConfiguracion.chipcard_oper_auto);
}
// a partir de aquí continuamos igual si es chipcard o no...
LogTarisan.logger.log(NivelLog.DEBUG, "LLega 1949");
if(respuesta_correcta)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Chipcard Autoriza, vamos a insertar en tamovext");
aValores[12] = Integer.valueOf(respuesta.get_talon_chipcard());//talon_chipcard
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Desplazado, siempre autorizamos");
aValores[12] = Integer.valueOf(0);
}
if((respuesta_correcta) || (entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_adeslas) != 0))
{
//insertamos en tamovext para que se le facture al médico.
/*
* Comprobar antes de insertar en tamovex comprobar el talon_chipcard existe para otro medico
* Si existe ERROR!!
*
*/
if(perTamovext.insertarTamovextDesplazado(aValores, conexion))
{
//actualizamos el valor de la primera visita en caso de que sea necesario
if (( strCodigoActos.indexOf("¬" + ParametrosConfiguracion.codigoPrimeraVisita + "¬") != -1 ) && (tar.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_propios)==0 )){ //se ha seleccionado el acto medico PRIMERA VISITA
acto = ParametrosConfiguracion.codigoPrimeraVisita;
actualizarPrimeraVisita(intMedico, tar.getColectivo(), tar.getPoliza(), tar.getBeneficiario(), acto, conexion);
}
//actualizamos el valor de la primera limpieza en caso de que sea necesario
if (( strCodigoActos.indexOf("¬" + ParametrosConfiguracion.codigoPrimeraLimpieza + "¬") != -1 ) && (tar.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_propios)==0)){ //se ha seleccionado el acto medico PRIMERA LIMPIEZA
acto = ParametrosConfiguracion.codigoPrimeraLimpieza;
actualizarPrimeraLimpieza(intMedico, tar.getColectivo(), tar.getPoliza(), tar.getBeneficiario(), acto, conexion);
}
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha insertado correctamente el movimiento en tamovext.");
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
StringBuffer strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVEXT");
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, TARJETA_CHIPCARD, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD, TALON_CHIPCARD, ENTIDAD, AUTORIZACION)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVEXT", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
//intUltimoValorNumSeq++;
//Insertar en tadesplaz
/*
* CREATE TABLE ALBERTO.TADESPLAZ
(
TARJETA_CHIPCARD CHAR(24 BYTE),
NOMBRE_COMPLETO CHAR(30 BYTE),
FECHA_ALTA DATE,
ENTIDAD_CHIPCARD NUMBER(4),
CONTRATO_CHIPCARD NUMBER(3),
FECHA_REGISTRO DATE,
TRATADO NUMBER(1)
)
*/
/* if(tar.getColectivo() == 0 && tar.getPoliza() == 0)
{
Tadespla tades = new Tadespla();
PersistenciaTaDespla perTaDes = new PersistenciaTaDespla();
tades = perTaDes.Seleccionar_Tadespla(tarjetaDesplazado);
LogTarisan.logger.log(NivelLog.DEBUG, "1390 - Contrato en tarjeta vale: "+contrato);
tades.setContrato(tar.getContrato());
if(tades.getContrato() == 0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nOJO SE HA PUESTO UN CONTRATO A FUEGO\n\n");
LogTarisan.logger.log(NivelLog.DEBUG, "Contrato en tarjeta vale: "+tar.getContrato());
LogTarisan.logger.log(NivelLog.DEBUG, "Contrato en despla vale: "+tades.getContrato());
tades.setContrato(1);
}
java.sql.Date fecha_reg = new java.sql.Date(Calendar.getInstance().getTimeInMillis());
tades.setFecha_Registro(fecha_reg);
tades.set_tarjeta(tar.getTarjetaDesplazado());
tades.setEntidad_chipcard(tar.getEntidadIMQ());
tades.setFecha_Alta(fecha_reg);
tades.setNombre(((Paciente)sesion.getAttribute("PACIENTE")).getNombre());
tades.setResultado(0);
if(((Paciente)sesion.getAttribute("PACIENTE")).getIdentificador() != null)
{
tades.setTroquelado(((Paciente)sesion.getAttribute("PACIENTE")).getIdentificador());
}
else
tades.setTroquelado("");
if (perTaDes.Insertar_Tadespla(tades))
LogTarisan.logger.log(NivelLog.DEBUG, "Se inserta correctamente en tades");
else
LogTarisan.logger.log(NivelLog.DEBUG, "Error al insertar en tades");
}*/
sesion.setAttribute("mensaje", "<font color='blue'>Se ha facturado el acto correctamente</font>");
}
else
{
//sesion.setAttribute("mensaje", "<font color='red'>No se ha podido facturar el acto...</font>");
sesion.setAttribute("mensaje", "<font color='red'>"+ tamensaje.getMensaje() +"..</font>");
}
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Chipcard NO Autoriza. DENEGADA");
int pos = respuesta.get_mensaje().indexOf(" - ");
pos += 2;
if(respuesta.get_respuesta().contains(ParametrosConfiguracion.chipcard_oper_auto))
sesion.setAttribute("mensaje", "<font color='red'>"+ tamensaje.getMensaje() +" <br/><br/></font>");
else
sesion.setAttribute("mensaje", "<font color='red'>"+ tamensaje.getMensaje() +" <br/><br/>Respuesta de la entidad emisora: "+respuesta.get_respuesta()+"<br/>Motivo: "+ respuesta.get_mensaje().substring(pos)+"</font>");
/*if(respuesta.get_respuesta().contains(ParametrosConfiguracion.chipcard_oper_auto))
sesion.setAttribute("mensaje", "<font color='red'>"+"No se ha podido facturar el acto. <br/><br/></font>");
else
sesion.setAttribute("mensaje", "<font color='red'>"+"No se ha podido facturar el acto. <br/><br/>Respuesta de la entidad emisora: "+respuesta.get_respuesta()+"<br/>Motivo: "+ respuesta.get_mensaje().substring(pos)+"</font>");*/
}
}
}
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
private boolean facturacionSesionRehabPod(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
boolean resultado = false;
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
long autorizacion = Long.valueOf(request.getParameter("autorizacion"));
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "GestorPacientes.java - facturacionSesionRehabPod - Inicio");
PersistenciaTaconaut perTaconaut = new PersistenciaTaconaut();
//RestarSesion(int autorizacion, int medico, int acto, int especialidad)
String strCodigoActos = (String)request.getParameter("listaCodigoElementosPrescripcion");
String limpio = strCodigoActos.replaceAll("Â", "");
strCodigoActos = limpio;
int intEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
int intTarifa = ((Usuario)sesion.getAttribute("USUARIO")).getTarifa();
int intEntidad = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadIMQ();
long intColectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double dblPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
int intBeneficiario = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
String tarjetaChipcard = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado();
if(tarjetaChipcard == null)
tarjetaChipcard = "";
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
PersistenciaTamovext perTamovext = new PersistenciaTamovext();
//int intUltimoValorNumSeq = perTamovext.obtenerUltimoValorNumSeq(intMedico);
PersistenciaTtactmed perttactmed = new PersistenciaTtactmed();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
int intUltimoValorCorrelativo = perTareglog.obtenerUltimoValorCorrelativo(intMedico, tsFechaUltimoAcceso);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 2108: StrCodigoActos: "+strCodigoActos);
limpio = strCodigoActos.replaceAll("Â", "");
StringTokenizer st = new StringTokenizer(limpio, "¬");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 2111: StrCodigoActosLimpio: "+limpio);
String actos="";
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
boolean error = false;
while (st.hasMoreTokens() && !error)
{
//obtenemos los valores especificos para cada acto medico
int acto = Integer.parseInt( st.nextToken() );
//hacemos la insert en tamovext para que se le facture al médico
/*
* strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
*/
Object [] aValores = new Object[14];
aValores[0] = Integer.valueOf(intMedico);
aValores[1] = Integer.valueOf(intEspecialidad);
aValores[2] = Integer.valueOf(acto);
//aValores[3] = Integer.valueOf(intUltimoValorNumSeq + 1);
aValores[3] = Long.valueOf(intColectivo);
aValores[4] = Double.valueOf(dblPoliza);
aValores[5] = Integer.valueOf(intBeneficiario);
aValores[6] = dtFecha;
aValores[7] = Double.valueOf(perttactmed.obtenerPrecioActoMedico(intTarifa, acto, intEspecialidad));
aValores[8] = Integer.valueOf(intMedico);
aValores[9] = Integer.valueOf(intEntidad);
aValores[10] = new String(tarjetaChipcard);
aValores[11] = Long.valueOf(autorizacion);
aValores[12] = Integer.valueOf(intEspecialidad);
aValores[13] = Integer.valueOf(acto);
//intUltimoValorNumSeq++;
actos += String.valueOf(acto);
actos += ", ";
//Hacer que si es adeslas compruebe con chipcard:
/*String pista2 = Utilidades.extraerPista2(valorTarjeta);
String talon_chipcard = Tarisan.check_card(ParametrosConfiguracion.chipcard_login, ParametrosConfiguracion.chipcard_pass, Integer.parseInt(ParametrosConfiguracion.chipcard_terminal), Integer.parseInt(ParametrosConfiguracion.chipcard_company), ParametrosConfiguracion.chipcard_url, pista2, ParametrosConfiguracion.chipcard_profesional, 40, Integer.parseInt(ParametrosConfiguracion.chipcard_lista), 1);
Thread.sleep(1510);
LogTarisan.logger.log(NivelLog.DEBUG, "El tvs devuelve: "+talon_chipcard);
RespuestaChipcard respuesta = new RespuestaChipcard();
PersistenciaRespuestaChipcard perRes = new PersistenciaRespuestaChipcard();
respuesta = perRes.parsearRespuesta(talon_chipcard);
sMensaje = "La tarjeta de Adeslas Respuesta de chipcard Error? "+respuesta.get_error()+": <br/>terminal: "+respuesta.get_terminal()+"<br/>respuesta: "+respuesta.get_respuesta() +"<br/>mensaje: "+ respuesta.get_mensaje() +"<br/>num_aut: "+respuesta.get_talon_chipcard();
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;*/
/*
* Marimar ticket 734133
* Algunos médicos usan 2 ordenadores y consiguen imputar el mismo acto el mismo día...
*
*
* public boolean PermitirImputarActo(long autorizacion, int especialidad, int acto, String tarjeta)
*/
PersistenciaTaconaut pertaconaut = new PersistenciaTaconaut();
if(!pertaconaut.PermitirImputarActo(autorizacion,intEspecialidad,acto,""))
{
LogTarisan.logger.log(NivelLog.INFO, "Medico listillo desde 2 equipos a la vez no le dejamos cargarse otro acto");
throw new ExcepcionTarisan("Doble facturacion");
}
//insertamos en tamovext para que se le facture al médico.
if(perTamovext.insertarTamovext(aValores, conexion))
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha insertado correctamente el movimiento en tamovext. Rehabilitacion, autorizacion: " + autorizacion);
}
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
StringBuffer strSql = new StringBuffer();
int perfilsesion = Integer.parseInt((String)sesion.getAttribute("PERFIL"));
strSql.append("INSERT INTO TAMOVEXT");// (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, autorizacion) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVEXT", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
if(perfilsesion == Integer.parseInt(Constantes.PERFIL_ATS) && ParametrosConfiguracion.actos_ats_curas.contains(String.valueOf(acto)))
{
if(perTaconaut.ActualizarFechaModificacion(autorizacion, acto, intEspecialidad))
LogTarisan.logger.log(NivelLog.INFO, "No restamos de taconaut por que es una cura, pero actualizamos su fecha de modificacion");
}
else
{
boolean restar = false;
if(perfilsesion == Integer.parseInt(Constantes.PERFIL_ATS))
restar = perTaconaut.RestarSesion(autorizacion, acto, intEspecialidad);
//restar = perTaconaut.RestarSesion(Aut, Med, acto, intEspecialidad);
else
restar = perTaconaut.RestarSesion(autorizacion, intMedico, acto, intEspecialidad);
if(restar)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha restado correctamente la sesion a la autorizacion:" + autorizacion);
}
else
{
LogTarisan.logger.log(NivelLog.ERROR, "No se ha restado de taconaut la sesion de la autorizacion: " + autorizacion);
error = true;
}
}
}
if(!error)
{
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
resultado = true;
}
else
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
sesion.setAttribute("RESULTADO", "Se ha imputado correctamente el acto: " + actos.substring(0, actos.length()-2));
LogTarisan.logger.log(NivelLog.DEBUG, "GestorPacientes.java - facturacionSesionRehabPod - Fin");
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion: " + ex + ". En la autorizacion: " + autorizacion);
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
throw new ExcepcionTarisan(ex.getMessage());
}
return resultado;
}
/**
* Realiza la facturación de los actos prescribibles.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private boolean facturacionActosPrescribibles(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
boolean resultado = false;
try
{
int intTarifa = ((Usuario)sesion.getAttribute("USUARIO")).getTarifa();
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long intColectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double dblPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
int intBeneficiario = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
int intEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
int intEntidad = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadIMQ();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String strCodigoActos = (String)request.getParameter("listaCodigoElementosPrescripcion");
String limpio = strCodigoActos.replaceAll("Â", "");
strCodigoActos = limpio;
LogTarisan.logger.log(NivelLog.DEBUG, "llega 1527");
String tarjetaChipcard = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado();
if(tarjetaChipcard == null)
tarjetaChipcard = "";
int actoErroneo = 0;
int intCodActo=0;
//comprobamos si la poliza es una de las igualas del medico
PersistenciaTapolfac perTapolfac = new PersistenciaTapolfac();
Integer blnEsPolizaIgualaMedico = perTapolfac.esPolizaIgualaMedico(intMedico, intColectivo, dblPoliza);
//obtenemos el perfil del medico
String perfil = (String)sesion.getAttribute("PERFIL");
//Si el médico es especialista (no es de cabecera) o el médico es de cabecera pero la póliza no es igualas puede continuar
if (perfil.equalsIgnoreCase(Constantes.PERFIL_ESPECIALISTA) || perfil.equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA) || (perfil.equalsIgnoreCase(Constantes.PERFIL_CABECERA) && (blnEsPolizaIgualaMedico == 0)) || perfil.equalsIgnoreCase(Constantes.PERFIL_DENTISTA))
{
PersistenciaTamovext perTamovext = new PersistenciaTamovext();
PersistenciaTtactmed perttactmed = new PersistenciaTtactmed();
PersistenciaTamovmpo perTamovmpo = new PersistenciaTamovmpo();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
PersistenciaTaprimer perTaprimer = new PersistenciaTaprimer();
//obtenemos el ultimo valor del campo numseq de la tabla tamovext.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
/*
* Cambiamos este campo a tipo autoincrement en oracle.
int intUltimoValorNumSeq = perTamovext.obtenerUltimoValorNumSeq(intMedico);
*/
//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);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
limpio = strCodigoActos.replaceAll("Â", "");
StringTokenizer st = new StringTokenizer(limpio, "¬");
boolean seguir = true;
while (st.hasMoreTokens() && seguir)
{
//obtenemos los valores especificos para cada acto medico
intCodActo = Integer.parseInt( st.nextToken() );
seguir = perTaprimer.sePuedeAutoprescribible(intMedico, intEntidad, intColectivo, dblPoliza, intBeneficiario, intCodActo);
if(!seguir)
actoErroneo = intCodActo;
}
if(seguir)
{
try
{
//introducimos para cada acto medico un nuevo registro en la tabla movext
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVEXT");
//strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)"); //
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
//inicializamos el array con los valores fijos
aValores = new Object[14];
aValores[0] = Integer.valueOf(intMedico);
aValores[1] = Integer.valueOf(intEspecialidad);
aValores[3] = Long.valueOf(intColectivo);
aValores[4] = Double.valueOf(dblPoliza);
aValores[5] = Integer.valueOf(intBeneficiario);
aValores[6] = dtFecha;
aValores[8] = Integer.valueOf(intMedico);
aValores[9] = Integer.valueOf(intEntidad);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 2316");
aValores[10] = new String(tarjetaChipcard);
aValores[11] = Integer.valueOf(0);
aValores[12] = Integer.valueOf(intEspecialidad);
intCodActo=0;
st = new StringTokenizer(strCodigoActos, "¬");
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 2325");
while (st.hasMoreTokens())
{
//obtenemos los valores especificos para cada acto medico
intCodActo = Integer.parseInt( st.nextToken() );
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 2330");
aValores[2] = Integer.valueOf(intCodActo);
// Cambiar acto_chipcard
int actoChipcard = intCodActo;
PersistenciaTamovext perTamovex = new PersistenciaTamovext();
if(perTamovex.esPrimeraVisitaDesplazado(intMedico, tarjetaChipcard, true))
{
if(intCodActo == 2 && !perTamovext.tieneConsultaChipcard(intMedico, tarjetaChipcard))
actoChipcard = 1;
if(intCodActo == 1 && perTamovext.tieneConsultaChipcard(intMedico, tarjetaChipcard))
actoChipcard = 2;
}
aValores[13] = Integer.valueOf(actoChipcard);
//aValores[3] = Integer.valueOf(intUltimoValorNumSeq + 1);
aValores[7] = Double.valueOf( perttactmed.obtenerPrecioActoMedico(intTarifa, intCodActo, intEspecialidad) );
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 1605");
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes - Obtener precio acto medico con intTarifa="+intTarifa+", intCodActo="+intCodActo+", intEspecialidad="+intEspecialidad+"\n\n");
//intUltimoValorNumSeq++;
//hay que insertar los valores de chipcard para todos los movimientos
//insertamos el registro
//perTamovext.insertarMovimiento(strSql.toString(), aValores, conexion);
perTamovext.insertarTamovext(aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVEXT");
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVEXT", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//introducimos para cada acto medico un nuevo registro en la tabla tamovmpo
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVMPO");
strSql.append(" (MEDICO, COLEC, POLIZA, ORDEN, FECHA, NUMERO, TEXTO)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?)");
//inicializamos el array con los valores fijos
aValores = new Object[7];
aValores[0] = Integer.valueOf(intMedico);
aValores[1] = Long.valueOf(intColectivo);
aValores[2] = Double.valueOf(dblPoliza);
aValores[3] = Integer.valueOf(intBeneficiario);
aValores[4] = dtFecha;
//obtenemos el ultimo valor del campo numseq de la tabla movext.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorNumero = perTamovmpo.obtenerUltimoNumero(intMedico, intColectivo, dblPoliza, intBeneficiario, dtFecha);
st = new StringTokenizer((String)request.getParameter("listaElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
aValores[5] = Integer.valueOf(intUltimoValorNumero + 1);
aValores[6] = st.nextToken();
intUltimoValorNumero++;
//insertamos el registro
perTamovmpo.insertarMovimiento(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVMPO", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor de la primera visita en caso de que sea necesario
if ( strCodigoActos.indexOf("¬" + ParametrosConfiguracion.codigoPrimeraVisita + "¬") != -1 ){ //se ha seleccionado el acto medico PRIMERA VISITA
intCodActo = ParametrosConfiguracion.codigoPrimeraVisita;
actualizarPrimeraVisita(intMedico, intColectivo, dblPoliza, intBeneficiario, intCodActo, conexion);
}
//actualizamos el valor de la primera limpieza en caso de que sea necesario
if ( strCodigoActos.indexOf("¬" + ParametrosConfiguracion.codigoPrimeraLimpieza + "¬") != -1 ){ //se ha seleccionado el acto medico PRIMERA LIMPIEZA
intCodActo = ParametrosConfiguracion.codigoPrimeraLimpieza;
actualizarPrimeraLimpieza(intMedico, intColectivo, dblPoliza, intBeneficiario, intCodActo, conexion);
}
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
resultado = true;
}
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);
}
}
else
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha intentado prescribir dos veces un acto autoprescribible");
if(perfil.equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA))
sesion.setAttribute("VUELTA", "No puede imputar el acto");
sesion.setAttribute("ERROR", "No puede imputar el acto "+perttactmed.obtenerNombreActo(actoErroneo, intEspecialidad).trim()+", por que ya se le ha imputado hoy.");
}
}
}
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());
}
return resultado;
}
private boolean facturacionActosPrescribiblesEstomatologia(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
boolean resultado = false;
try
{
int intContrato = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getContrato();
int intTarifa = ((Usuario)sesion.getAttribute("USUARIO")).getTarifa();
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long intColectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double dblPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
int intBeneficiario = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
int intEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
int intEntidad = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadIMQ();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String strCodigoActos = (String)request.getParameter("listaCodigoElementosPrescripcion");
String limpio = strCodigoActos.replaceAll("Â", "");
strCodigoActos = limpio;
LogTarisan.logger.log(NivelLog.DEBUG, "llega 1527");
String tarjetaChipcard = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado();
if(tarjetaChipcard == null)
tarjetaChipcard = "";
int actoErroneo = 0;
int intCodActo=0;
//comprobamos si la poliza es una de las igualas del medico
PersistenciaTapolfac perTapolfac = new PersistenciaTapolfac();
Integer blnEsPolizaIgualaMedico = perTapolfac.esPolizaIgualaMedico(intMedico, intColectivo, dblPoliza);
//obtenemos el perfil del medico
String perfil = (String)sesion.getAttribute("PERFIL");
//Si el médico es especialista (no es de cabecera) o el médico es de cabecera pero la póliza no es igualas puede continuar
if (perfil.equalsIgnoreCase(Constantes.PERFIL_ESPECIALISTA) || perfil.equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA) || (perfil.equalsIgnoreCase(Constantes.PERFIL_CABECERA) && (blnEsPolizaIgualaMedico == 0)) || perfil.equalsIgnoreCase(Constantes.PERFIL_DENTISTA))
{
PersistenciaTamovextDental perTamovextDental = new PersistenciaTamovextDental();
PersistenciaTtactmed perttactmed = new PersistenciaTtactmed();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
PersistenciaTaprimer perTaprimer = new PersistenciaTaprimer();
//obtenemos el ultimo valor del campo numseq de la tabla tamovext.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorNumSeq = perTamovextDental.obtenerUltimoValorNumSeq(intMedico);
//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);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
StringTokenizer st = new StringTokenizer(strCodigoActos, "¬");
boolean seguir = true;
while (st.hasMoreTokens() && seguir)
{
//obtenemos los valores especificos para cada acto medico
intCodActo = Integer.parseInt( st.nextToken() );
//seguir = perTaprimer.sePuedeAutoprescribible(intMedico, intEntidad, intColectivo, dblPoliza, intBeneficiario, intCodActo,intContrato);
//seguir = perTaprimer.sePuedeAutoprescribible(intMedico, intEntidad, intColectivo, dblPoliza, intBeneficiario, intCodActo);
// TODO
// permitimos insertar todos los actos todas las veces que quieran
seguir = true;
if(!seguir)
actoErroneo = intCodActo;
}
if(seguir)
{
try
{
//introducimos para cada acto medico un nuevo registro en la tabla movext_dental
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVEXT_DENTAL");
//strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)"); //
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
//inicializamos el array con los valores fijos
aValores = new Object[15];
aValores[0] = Integer.valueOf(intMedico);
aValores[1] = Integer.valueOf(intEspecialidad);
aValores[4] = Long.valueOf(intColectivo);
aValores[5] = Double.valueOf(dblPoliza);
aValores[6] = Integer.valueOf(intBeneficiario);
aValores[7] = dtFecha;
aValores[9] = Integer.valueOf(intMedico);
aValores[10] = Integer.valueOf(intEntidad);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 1591");
aValores[11] = new String(tarjetaChipcard);
aValores[12] = Integer.valueOf(0);
aValores[13] = Integer.valueOf(intEspecialidad);
intCodActo=0;
st = new StringTokenizer(strCodigoActos, "¬");
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 1596");
while (st.hasMoreTokens())
{
//obtenemos los valores especificos para cada acto medico
intCodActo = Integer.parseInt( st.nextToken() );
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 1601");
aValores[2] = Integer.valueOf(intCodActo);
aValores[14] = Integer.valueOf(intCodActo);
aValores[3] = Integer.valueOf(intUltimoValorNumSeq + 1);
// TODO
// Ver si queremos seguir sacando los precios desde ttactmed o desde ttfranquicias...
aValores[8] = Double.valueOf( perttactmed.obtenerPrecioActoMedico(intTarifa, intCodActo, intEspecialidad) );
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes 1605");
LogTarisan.logger.log(NivelLog.DEBUG, "\n\nGestorPacientes - Obtener precio acto medico con intTarifa="+intTarifa+", intCodActo="+intCodActo+", intEspecialidad="+intEspecialidad+"\n\n");
intUltimoValorNumSeq++;
//hay que insertar los valores de chipcard para todos los movimientos
//insertamos el registro
//perTamovext.insertarMovimiento(strSql.toString(), aValores, conexion);
perTamovextDental.insertarTamovextDental(aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVEXT_DENTAL");
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
intUltimoValorCorrelativo++;
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVEXT_DENTAL", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor de la primera visita en caso de que sea necesario
if ( strCodigoActos.indexOf("¬" + ParametrosConfiguracion.codigoPrimeraVisita + "¬") != -1 ){ //se ha seleccionado el acto medico PRIMERA VISITA
intCodActo = ParametrosConfiguracion.codigoPrimeraVisita;
actualizarPrimeraVisita(intMedico, intColectivo, dblPoliza, intBeneficiario, intCodActo, conexion);
}
//actualizamos el valor de la primera limpieza en caso de que sea necesario
if ( strCodigoActos.indexOf("¬" + ParametrosConfiguracion.codigoPrimeraLimpieza + "¬") != -1 ){ //se ha seleccionado el acto medico PRIMERA LIMPIEZA
intCodActo = ParametrosConfiguracion.codigoPrimeraLimpieza;
actualizarPrimeraLimpieza(intMedico, intColectivo, dblPoliza, intBeneficiario, intCodActo, conexion);
}
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
resultado = true;
}
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);
}
}
else
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha intentado prescribir dos veces un acto autoprescribible");
if(perfil.equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA))
sesion.setAttribute("VUELTA_DENTAL", "No puede imputar el acto");
sesion.setAttribute("ERROR", "No puede imputar el acto "+perttactmed.obtenerNombreActo(actoErroneo, intEspecialidad).trim()+", por que ya se le ha imputado hoy.");
}
}
}
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());
}
return resultado;
}
/**
* Se actualizan las tablas TAMOVEXT y TARESANA para grabar la aceptación del análisis prescrito.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private int aceptarAnalisisPrescrito(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
try
{
PersistenciaTamovext perTamovext = new PersistenciaTamovext();
PersistenciaTaresana perTaresana = new PersistenciaTaresana();
PersistenciaTtactmed perttactmed = new PersistenciaTtactmed();
PersistenciaTapresca pertapresca_tarisan = new PersistenciaTapresca();
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
PersistenciaTapecap perTapecap = new PersistenciaTapecap();
PersistenciaTabenefi perTaben = new PersistenciaTabenefi();
//obtenemos los datos del medico y del paciente
int intTarifa = ((Usuario)sesion.getAttribute("USUARIO")).getTarifa();
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
int intEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
int intEntidad = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadIMQ();
long longColectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double dblPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
String strEmbosado = ((Paciente)sesion.getAttribute("PACIENTE")).getIdentificador();
if (strEmbosado == null)
strEmbosado = "";
int intBeneficiario = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
long longAutorizacion = Long.parseLong( (String)request.getParameter("autorizacion") );
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String tarjetaChipcard = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado();
if (tarjetaChipcard == null)
tarjetaChipcard = "";
/*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 numseq de la tabla tamovext.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
//int intUltimoValorNumSeq = perTamovext.obtenerUltimoValorNumSeq(intMedico);
//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);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVEXT");
//strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, NUMSEQ, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
//quito el campo numseq por que hacemos un autoincrement en el oracle
strSql.append(" (MEDICO, ESPECIALIDAD, ACTO, COLECTIVO, POLIZA, ORDEN, FECHA, PRECIO, PRESCRIPTOR, ENTIDAD, TARJETA_CHIPCARD, AUTORIZACION, ESPECIALIDAD_CHIPCARD, ACTO_CHIPCARD)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
//inicializamos el array con los valores fijos
aValores = new Object[14];
aValores[0] = Integer.valueOf(intMedico);
aValores[1] = Integer.valueOf(intEspecialidad);
aValores[3] = Long.valueOf(longColectivo);
aValores[4] = Double.valueOf(dblPoliza);
aValores[5] = Integer.valueOf(intBeneficiario);
aValores[6] = dtFecha;
Tamedico taprescriptor = perTamedico.obtenerMedicoPrescripcionAnalisis(longAutorizacion, longColectivo, dblPoliza, intBeneficiario);
aValores[8] = Integer.valueOf(taprescriptor.getMedico());
aValores[9] = Integer.valueOf(intEntidad);
aValores[10] = new String(tarjetaChipcard);
aValores[11] = Long.valueOf(longAutorizacion);
aValores[12] = Integer.valueOf(intEspecialidad);
int intCodActo=0;
LogTarisan.logger.log(NivelLog.DEBUG, "Forzar un commit");
Vector vAnalisis = pertapresca_tarisan.obtenerActosPrescripcionAnalisis(longAutorizacion, longColectivo, dblPoliza, intBeneficiario, 0);
Tapresca tapresca_tarisan = null;
for(int i = 0; i < vAnalisis.size(); i++)
{
//obtenemos los valores especificos para cada acto medico
tapresca_tarisan = (Tapresca)vAnalisis.elementAt(i);
intCodActo = tapresca_tarisan.getActo();
double precio = perttactmed.obtenerPrecioActoMedico(intTarifa, intCodActo, intEspecialidad);
aValores[2] = Integer.valueOf(intCodActo);
aValores[13] = Integer.valueOf(intCodActo);
//aValores[3] = Integer.valueOf(intUltimoValorNumSeq + 1);
aValores[7] = Double.valueOf( precio );
if (precio == -1){
//No se ha encontrado el precio del acto. Salimos
return 2;//Saco mensaje de que no hay precio
}
//intUltimoValorNumSeq++;
//insertamos el registro
//perTamovext.insertarMovimiento(strSql.toString(), aValores, conexion);
perTamovext.insertarTamovext(aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVEXT", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//introducimos un nuevo registro en la tabla taresana
strSql = new StringBuffer();
strSql.append("INSERT INTO TARESANA");
strSql.append(" (PRESCRIPTOR, ESPECIALIDAD, COLEC, POLIZA, ORDEN, FECHA, AUTORIZACION, LABORATORIO)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
//cargamos el array
aValores = new Object[8];
aValores[0] = Integer.valueOf(taprescriptor.getMedico());
aValores[1] = Integer.valueOf(intEspecialidad);
aValores[2] = Long.valueOf(longColectivo);
aValores[3] = Double.valueOf(dblPoliza);
aValores[4] = Integer.valueOf(intBeneficiario);
aValores[5] = dtFecha;
aValores[6] = Long.valueOf(longAutorizacion);
aValores[7] = Integer.valueOf(intMedico);
perTaresana.insertarAnalisis(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TARESANA", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
//introducimos un nuevo registro en la tabla tapecap
String consulta = "";
aValores = new Object[0];
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, ?, TO_DATE('?','dd/mm/yyyy'), ?, ?, ?, ?, TO_DATE('?','dd/mm/yyyy'), ?, ?, ?, ?, ?, ?, ?, ?, ?, ? FROM DUAL");
PersistenciaTamedico perTame = new PersistenciaTamedico();
Tamedico tamedico = new Tamedico();
tamedico = perTame.seleccionar(taprescriptor.getMedico());
PersistenciaTaespeci perTaespeci = new PersistenciaTaespeci();
String descripEspe = "";
descripEspe = perTaespeci.obtenerDescripcionEspecialidad(tamedico.getEspecialidad());
int intUltimoValorCodigo = perTapecap.obtenerUltimoCodigo(intMedico);
//cargamos el array
Vector vDatosPaciente = new Vector();
vDatosPaciente = perTapecap.obtenerDetallePaciente(longColectivo, dblPoliza, intBeneficiario);
if (vDatosPaciente.isEmpty()){
//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.
/*if (perTapecap.existePaciente(intMedico, strEmbosado)){
int num = 0;
strCodigo = perTapecap.obtenerUltimoCodigoMismoPaciente(intMedico,strEmbosado);
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;
}
}*/
String fecha = dtFecha.toString().substring(8)+"/"+dtFecha.toString().substring(5, 7)+"/"+dtFecha.toString().substring(0, 4);
consulta = "INSERT INTO TAPECAP (TAPECAP_PK, CODIGO, FECHA, APELLIDOS, NOMBRE, NIF, DIRECCION, FECHA_NAC, TELEFONO, COMPAÑIA, IDENTIFICADOR, MEDICO, AUTORIZACION, PRESCRIPTOR, ESPECIALIDAD, POLIZA, COLECTIVO, ORDEN) SELECT TAPECAP_PK_SEQ.NEXTVAL, '"+ intUltimoValorCodigo +"', TO_DATE('"+fecha+"','dd/mm/yyyy'), '', '', '', '', '', '', '', '"+ strEmbosado +"', "+ intMedico +", "+ longAutorizacion +", '"+ tamedico.getApellidos().trim() +"', '"+ descripEspe.trim() +"', -1, -1, -1 FROM DUAL";
//consulta = "INSERT INTO TAPECAP (TAPECAP_PK, CODIGO, FECHA, APELLIDOS, NOMBRE, NIF, DIRECCION, FECHA_NAC, TELEFONO, COMPAÑIA, IDENTIFICADOR, MEDICO, AUTORIZACION, PRESCRIPTOR, ESPECIALIDAD, POLIZA, COLECTIVO, ORDEN) SELECT TAPECAP_PK_SEQ.NEXTVAL, '"+ intUltimoValorCodigo +"', TO_DATE('"+ (String)Utilidades.formatear_fecha(dtFecha) +"','dd/mm/yyyy'), '', '', '', '', '', '', '', '"+ strEmbosado +"', "+ intMedico +", "+ longAutorizacion +", '"+ tamedico.getApellidos().trim() +"', '"+ descripEspe.trim() +"', -1, -1, -1 FROM DUAL";
}else{
//Sacamos el troquelado de la tarjeta (que es lo que en GINFER llaman póliza)
String troque = "";
troque = perTaben.obtenerIdentificador(longColectivo, dblPoliza, intBeneficiario);
//troque.trim();
String embo = "";
if (strEmbosado.compareTo("")!=0){ //Si está el troquelado en sesion lo cogemos
embo = strEmbosado;
}else{ //Si no esta en sesión, lo cogemos de ttbenefi
if(troque.compareTo("")!=0 || troque!=""){
embo = troque;
}else{
long tj = 0;
tj = perTaben.obtenerTarjeta(longColectivo, dblPoliza, intBeneficiario);
embo = ""+tj;
}
}
//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.
/*if (perTapecap.existePaciente(intMedico, embo)){
int num = 0;
strCodigo = perTapecap.obtenerUltimoCodigoMismoPaciente(intMedico,embo);
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;
}
}*/
String compa = "";
if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_propios)==0){
compa = "IMQ";
}else if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_adeslas)==0){
compa = "ADESLAS DESPLAZADO";
}else if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_dkv)==0){
compa = "DKV DESPLAZADO";
}else if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_sanitas)==0){
compa = "SANITAS DESPLAZADO";
}else if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_hna)==0){
compa = "HNA DESPLAZADO";
}else if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo)==0){
compa = "IMQ-BILBO DESPLAZADO";
}else if (((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_redsa_asisa)==0){
compa = "ASISA DESPLAZADO";
}
String fecha = dtFecha.toString().substring(8)+"/"+dtFecha.toString().substring(5, 7)+"/"+dtFecha.toString().substring(0, 4);
consulta = "INSERT INTO TAPECAP (TAPECAP_PK, CODIGO, FECHA, APELLIDOS, NOMBRE, NIF, DIRECCION, FECHA_NAC, TELEFONO, COMPAÑIA, IDENTIFICADOR, MEDICO, AUTORIZACION, PRESCRIPTOR, ESPECIALIDAD, POLIZA, COLECTIVO, ORDEN) SELECT TAPECAP_PK_SEQ.NEXTVAL, '"+ intUltimoValorCodigo +"', TO_DATE('"+fecha+"','dd/mm/yyyy'), '"+ (String)vDatosPaciente.elementAt(0) +"', '"+ (String)vDatosPaciente.elementAt(1) +"', '"+ (String)vDatosPaciente.elementAt(2) +"', '"+ (String)vDatosPaciente.elementAt(3) +"', '"+ (String)vDatosPaciente.elementAt(4) +"', '"+ (String)vDatosPaciente.elementAt(5) +"', '"+ compa +"', '"+ embo +"', "+ intMedico +", "+ longAutorizacion +", '"+ tamedico.getApellidos().trim() +"', '"+ descripEspe.trim() +"', "+ dblPoliza +", "+ longColectivo +", "+ intBeneficiario +" FROM DUAL";
// jjj fuerza el cambio y que compile
}
//perTapecap.insertarPeticionCapturada(strSql.toString(), aValores, conexion);
perTapecap.insertarPeticionCapturada(consulta, aValores, conexion);
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAPECAP", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
return 1;//Saco mensaje de "peticion adjudicada correctamente"
}
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());
}
}
/**
* Introduce en la tabla tapresca_tarisan la prescripción a otro médico especialista.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private void prescripcionEspecialidades(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
try
{
PersistenciaTapresca pertapresca_tarisan = new PersistenciaTapresca();
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos los datos del medico y del paciente
Paciente pac = (Paciente)sesion.getAttribute("PACIENTE");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long intColectivo = pac.getTarjeta().getColectivo();
double dblPoliza = pac.getTarjeta().getPoliza();
int intOrden = pac.getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String modifiAuto = (String)request.getParameter("modifiAuto");
String codigoEspecialidad = (String)request.getParameter("listaCodigoElementosPrescripcion");
//obtenemos el valor del campo param1 del medico conectado
//este valor se utiliza para calcular el numero de autorizacion para la prescripcion a realizar
int intParam1=perTamedico.obtenerValorParam1(intMedico);
//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);
//calculamos el numero de autorizacion para la prescripcion a realizar
long longAutorizacion = this.calcularCodigoAutorizacion(intMedico, intParam1);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
//Miramos si se trata de una modificación de la petición
if (modifiAuto.compareTo("")!=0 && (pertapresca_tarisan.existePeticion(Long.parseLong(modifiAuto)) && codigoEspecialidad.length()>0)){
//Eliminamos la analítica
strSql = new StringBuffer();
strSql.append("delete from tapresca_tarisan");
strSql.append(" where AUTORIZACION = ?");
aCondiciones= new Object[1];
aCondiciones[0] = Long.parseLong(modifiAuto);
//LogTarisan.logger.log(NivelLog.DEBUG, "Eliminamos la analitica: "+Utilidades.obtenerSentenciaSQL(strSql, aCondiciones, null));
boolean resultadoAnaliticaEliminada = pertapresca_tarisan.eliminarPrescripcion(strSql.toString(), aCondiciones, conexion);
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
aValores = new Object[13];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(modifiAuto);
aValores[6] = Integer.valueOf(0); //el acto medico lo metemos por defecto a '0'. No tiene sentido en este caso el acto medico, ya que tratamos especialidades.
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = ""; //dejamos vacio este campo
aValores[10] = ""; //dejamos vacio el campo texto
aValores[12] = 6; //TIPO_PETICION = ESPECIALIDAD
//aValores[11] = pac.getTarjeta().getTarjetaDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0 ? Integer.valueOf(pac.getTarjeta().getTarjeta()) : new String(pac.getTarjeta().getTarjetaDesplazado());
if (pac.getTarjeta().getTarjetaDesplazado()!=null){
if (pac.getTarjeta().getTarjetaDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0){
aValores[11] = Integer.valueOf(pac.getTarjeta().getTarjeta());
}else{
aValores[11] = new String(pac.getTarjeta().getTarjetaDesplazado());
}
}else{
aValores[11] = "";
}
/*String valo = (String)request.getParameter("listaCodigoElementosPrescripcion");
/* poner en listaCodigoElementosPrescripcion un ¬ si no lo tiene
if (((String)request.getParameter("listaCodigoElementosPrescripcion")).indexOf("¬")==-1){
request.setAttribute("listaCodigoElementosPrescripcion", (String)request.getParameter("listaCodigoElementosPrescripcion")+"¬");
}*/
//recorremos las especialidades prescritas y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer(codigoEspecialidad, "¬");
while (st.hasMoreTokens())
{
aValores[5] = Integer.valueOf( Integer.parseInt( st.nextToken() ) );
//actualizamos las prescripciones
LogTarisan.logger.log(NivelLog.DEBUG, Utilidades.obtenerSentenciaSQL(strSql, aValores, null));
pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
/*strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);*/
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(modifiAuto));
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
}else{
//Creamos la sentencia insert
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[13];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(longAutorizacion);
aValores[6] = Integer.valueOf(0); //el acto medico lo metemos por defecto a '0'. No tiene sentido en este caso el acto medico, ya que tratamos especialidades.
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = ""; //dejamos vacio este campo
aValores[10] = ""; //dejamos vacio el campo texto
aValores[12] = 6; //TIPO_PETICION = ESPECIALIDAD
//aValores[11] = pac.getTarjeta().getTarjetaDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0 ? Integer.valueOf(pac.getTarjeta().getTarjeta()) : new String(pac.getTarjeta().getTarjetaDesplazado());
if (pac.getTarjeta().getTarjetaDesplazado()!=null){
if (pac.getTarjeta().getTarjetaDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0){
aValores[11] = Integer.valueOf(pac.getTarjeta().getTarjeta());
}else{
aValores[11] = new String(pac.getTarjeta().getTarjetaDesplazado());
}
}else{
aValores[11] = "";
}
//recorremos las especialidades prescritas y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer((String)request.getParameter("listaCodigoElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
aValores[5] = Integer.valueOf( Integer.parseInt( st.nextToken() ) );
//actualizamos las prescripciones
pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(longAutorizacion));
//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());
}
}
/**
* Introduce en la tabla tapresca_tarisan la prescripción del diagnóstico.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private void prescripcionRadiodiagnosticos(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
try
{
PersistenciaTapresca pertapresca_tarisan = new PersistenciaTapresca();
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos los datos del medico y del paciente
Paciente pac = (Paciente)sesion.getAttribute("PACIENTE");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long intColectivo = pac.getTarjeta().getColectivo();
double dblPoliza = pac.getTarjeta().getPoliza();
int intOrden = pac.getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
//obtenemos el valor del campo param1 del medico conectado
//este valor se utiliza para calcular el numero de autorizacion para la prescripcion a realizar
int intParam1=perTamedico.obtenerValorParam1(intMedico);
//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);
//calculamos el numero de autorizacion para la prescripcion a realizar
long longAutorizacion = this.calcularCodigoAutorizacion(intMedico, intParam1);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
//Creamos la sentencia insert
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[13];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(longAutorizacion);
aValores[5] = Integer.valueOf(ParametrosConfiguracion.radiodiagnostico);
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = ""; //dejamos vacio este campo
aValores[10] = ""; //dejamos vacio este campo
aValores[12] = 3; //TIPO_PETICION = RADIOdiagnósticO
aValores[11] = pac.getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0 ? Integer.valueOf(pac.getTarjeta().getTarjeta()) : new String(pac.getTarjeta().getTarjetaDesplazado());
//recorremos los actos prescritos y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer((String)request.getParameter("listaCodigoElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
aValores[6] = Integer.valueOf( Integer.parseInt( st.nextToken() ) );
//actualizamos las prescripciones
pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(longAutorizacion));
//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());
}
}
/**
* Introduce en la tabla tapresca_tarisan la prescripción de la analítica.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private boolean prescripcionAnaliticas(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcion Analiticas y Anatomía Patológica - Entramos");
boolean result = false;
try
{
PersistenciaTapresca pertapresca_tarisan = new PersistenciaTapresca();
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos los datos del medico y del paciente
Paciente pac = (Paciente)sesion.getAttribute("PACIENTE");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long intColectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double dblPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
int intOrden = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String modifiAuto = (String)request.getParameter("modifiAuto");
int esp = Integer.valueOf(ParametrosConfiguracion.analiticas);
int tipo_peticion = 0;
String tipo = "";
if (request.getParameter("anato")!=null){
esp = 5;
LogTarisan.logger.log(NivelLog.DEBUG, "Anatomía Patológica");
tipo = "anatomía patológica";
tipo_peticion = 2;
}else{
LogTarisan.logger.log(NivelLog.DEBUG, "Analitica");
tipo = "analítica";
tipo_peticion = 1;
}
//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 valor del campo param1 del medico conectado
//este valor se utiliza para calcular el numero de autorizacion para la prescripcion a realizar
int intParam1=perTamedico.obtenerValorParam1(intMedico);
//calculamos el numero de autorizacion para la prescripcion a realizar
long longAutorizacion = this.calcularCodigoAutorizacion(intMedico, intParam1);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
if (modifiAuto.compareTo("")!=0 && (pertapresca_tarisan.existePeticion(Long.parseLong(modifiAuto)))){
//Eliminamos la analítica
strSql = new StringBuffer();
strSql.append("delete from tapresca_tarisan");
strSql.append(" where AUTORIZACION = ?");
aCondiciones= new Object[1];
aCondiciones[0] = Long.parseLong(modifiAuto);
//LogTarisan.logger.log(NivelLog.DEBUG, "Eliminamos la analitica: "+Utilidades.obtenerSentenciaSQL(strSql, aCondiciones, null));
boolean resultadoAnaliticaEliminada = pertapresca_tarisan.eliminarPrescripcion(strSql.toString(), aCondiciones, conexion);
//insertamos una nueva
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, JUSTIFY_DETER, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[14];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
/*aValores[4] = Long.valueOf(longAutorizacion); */
aValores[4] = Long.valueOf(modifiAuto);
aValores[5] = esp;
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = ""; //dejamos vacio este campo
aValores[10] = (String)request.getParameter("justificacionPrescripcion");
aValores[13] = tipo_peticion; //TIPO_PETICION = ANALÍTICA O ANATOMIA
if(pac.getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
aValores[11] = pac.getTarjeta().getTarjeta();
else
aValores[11] = pac.getTarjeta().getTarjetaDesplazado();
//recorremos los actos prescritos y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer((String)request.getParameter("listaCodigoElementosPrescripcion"), "¬");
StringTokenizer st2 = new StringTokenizer((String)request.getParameter("listaElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
int acto =Integer.parseInt( st.nextToken() );
String justify_acto = st2.nextToken();
aValores[6] = Integer.valueOf( acto );
if (justify_acto.indexOf("¬")==-1){
aValores[12] = new String("");
}else{
aValores[12] = new String(justify_acto.substring(justify_acto.indexOf(" ¬ ")+3));
}
//actualizamos las prescripciones
LogTarisan.logger.log(NivelLog.DEBUG, "Insertamos la "+tipo+": "+Utilidades.obtenerSentenciaSQL(strSql, aValores, null));
boolean resultado = pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
if(!resultado || !resultadoAnaliticaEliminada)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: Error al insertar la "+tipo+": "+(modifiAuto));
ExcepcionTarisan ex = new ExcepcionTarisan();
String sMensaje = "Se ha producido un error al guardar la "+tipo+".";
sesion.setAttribute("ERROR", sMensaje);
throw (ex);
}
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el numero de autorización rpovisional por el definitivo si ha sido una modificacion de la analítica
/*strSql = new StringBuffer();
strSql.append("UPDATE tapresca_tarisan");
strSql.append(" SET AUTORIZACION=?");
strSql.append(" WHERE AUTORIZACION=?");
aValores = new Object[1];
aValores[0] = Long.valueOf(Long.parseLong(modifiAuto));
aCondiciones = new Object[1];
aCondiciones[0] = Long.valueOf(longAutorizacion);
pertapresca_tarisan.modificarPrescripcion(strSql.toString(), aValores, aCondiciones, conexion);*/
}else{
//Creamos la sentencia insert
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, JUSTIFY_DETER, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[14];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(longAutorizacion);
aValores[5] = esp;
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = ""; //dejamos vacio este campo
aValores[10] = (String)request.getParameter("justificacionPrescripcion");
aValores[13] = tipo_peticion; //TIPO_PETICION = ANALÍTICA O ANATOMIA
if(pac.getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
aValores[11] = pac.getTarjeta().getTarjeta();
else
aValores[11] = pac.getTarjeta().getTarjetaDesplazado();
//recorremos los actos prescritos y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer((String)request.getParameter("listaCodigoElementosPrescripcion"), "¬");
StringTokenizer st2 = new StringTokenizer((String)request.getParameter("listaElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
int acto =Integer.parseInt( st.nextToken() );
String justify_acto = st2.nextToken();
/*
* int intContratonew = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getContrato();
* Persistenciattactmed perttactmed = new Persistenciattactmed();
* String descripcion = perttactmed.obtenerNombreActo(acto, ParametrosConfiguracion.analiticas);
* Vector vSeleccion = perttactmed.obtenerActosPorEspecialidad(1, ParametrosConfiguracion.analiticas,intContratonew,intColectivo,dblPoliza, descripcion);
//for(i=0;i<vSeleccion)
*
*/
aValores[6] = Integer.valueOf( acto );
if (justify_acto.indexOf("¬")==-1){
aValores[12] = new String("");
}else{
aValores[12] = new String(justify_acto.substring(justify_acto.indexOf(" ¬ ")+3));
}
//actualizamos las prescripciones
LogTarisan.logger.log(NivelLog.DEBUG, "Insertamos la "+tipo+": "+Utilidades.obtenerSentenciaSQL(strSql, aValores, null));
boolean resultado = pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
if(!resultado)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: Error al insertar la "+tipo+": "+longAutorizacion);
ExcepcionTarisan ex = new ExcepcionTarisan();
String sMensaje = "Se ha producido un error al guardar la "+tipo+".";
sesion.setAttribute("ERROR", sMensaje);
throw (ex);
}
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
}
long aut = 0;
if (modifiAuto.compareTo("")!=0){
aut = Long.valueOf(Long.parseLong(modifiAuto));
}else{
aut = Long.valueOf(longAutorizacion);
}
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(aut));
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcionAnaliticas - Transaccion confirmada");
strSql = new StringBuffer();
strSql.append("select count(*) cuantos from tapresca_tarisan where autorizacion = ? ");
aCondiciones = new Object[1];
aCondiciones[0] = Long.valueOf(aut);
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, strSql.toString(), aCondiciones);
while(rs.next())
{
if(rs.getInt("cuantos")>0)
{
result = true;
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha insertado bien la peticion: "+aut);
}
}
}
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);
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcionAnaliticas - Conexion liberada");
}
}
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());
}
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcion Analitica y Anatomía Patológica- Finalizada");
return result;
}
private boolean prescripcionDiagnosticos(HttpServletRequest request, HttpServletResponse response, HttpSession sesion, boolean justificacionNiveles) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcionDiagnosticos - Entramos");
boolean result = false;
try
{
PersistenciaTapresca pertapresca_tarisan = new PersistenciaTapresca();
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos los datos del medico y del paciente
Paciente pac = (Paciente)sesion.getAttribute("PACIENTE");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long intColectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double dblPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
int intOrden = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
//obtenemos el valor del campo param1 del medico conectado
//este valor se utiliza para calcular el numero de autorizacion para la prescripcion a realizar
int intParam1=perTamedico.obtenerValorParam1(intMedico);
//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);
//calculamos el numero de autorizacion para la prescripcion a realizar
long longAutorizacion = this.calcularCodigoAutorizacion(intMedico, intParam1);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
//Creamos la sentencia insert
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, JUSTIFY_DETER, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[14];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(longAutorizacion);
aValores[5] = Integer.valueOf(ParametrosConfiguracion.radiodiagnostico);
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = ""; //dejamos vacio este campo
aValores[13] = 3; //TIPO_PETICION = RADIOdiagnósticO
if (justificacionNiveles){
aValores[10] = (String)request.getParameter("justificacionPrescripcion");
}else{
aValores[10] ="";
}
//aValores[10] = (String)request.getParameter("justificacionPrescripcion");
if(pac.getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
aValores[11] = pac.getTarjeta().getTarjeta();
else
aValores[11] = pac.getTarjeta().getTarjetaDesplazado();
//recorremos los actos prescritos y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer((String)request.getParameter("listaCodigoElementosPrescripcion"), "¬");
StringTokenizer st2 = new StringTokenizer((String)request.getParameter("listaElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
int acto =Integer.parseInt( st.nextToken() );
String justify_acto = st2.nextToken();
/*
* int intContratonew = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getContrato();
* Persistenciattactmed perttactmed = new Persistenciattactmed();
* String descripcion = perttactmed.obtenerNombreActo(acto, ParametrosConfiguracion.analiticas);
* Vector vSeleccion = perttactmed.obtenerActosPorEspecialidad(1, ParametrosConfiguracion.analiticas,intContratonew,intColectivo,dblPoliza, descripcion);
//for(i=0;i<vSeleccion)
*
*/
aValores[6] = Integer.valueOf( acto );
if (justificacionNiveles){
aValores[12] = new String(justify_acto.substring(justify_acto.indexOf(" ¬ ")+3));
}else{
aValores[12] ="";
}
//aValores[12] = new String(justify_acto.substring(justify_acto.indexOf(" ¬ ")+3));
//actualizamos las prescriciones
LogTarisan.logger.log(NivelLog.DEBUG, "Insertamos la analitica: "+Utilidades.obtenerSentenciaSQL(strSql, aValores, null));
boolean resultado = pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
if(!resultado)
{
ParametrosConfiguracion.dataStore.deshacerTransaccion(conexion);
LogTarisan.logger.log(NivelLog.ERROR, "ExcepcionTarisan: Error al insertar el radiodiagnóstico: "+longAutorizacion);
ExcepcionTarisan ex = new ExcepcionTarisan();
String sMensaje = "Se ha producido un error al guardar el radiodiagnóstico.";
sesion.setAttribute("ERROR", sMensaje);
throw (ex);
}
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(longAutorizacion));
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcionDiagnostico - Transaccion confirmada");
strSql = new StringBuffer();
strSql.append("select count(*) cuantos from tapresca_tarisan where autorizacion = ? ");
aCondiciones[0] = Long.valueOf(longAutorizacion);
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, strSql.toString(), aCondiciones);
while(rs.next())
{
if(rs.getInt("cuantos")>0)
{
result = true;
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha insertado bien la peticion: "+longAutorizacion);
}
}
}
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);
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcionDiagnosticos - Conexion liberada");
}
}
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());
}
LogTarisan.logger.log(NivelLog.DEBUG, "prescripcionDiagnosticos - Finalizada");
return result;
}
/**
* Introduce en la tabla tapresca_tarisan la petición de autorización.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private void peticionAutorizacion(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql;
try
{
PersistenciaTapresca pertapresca_tarisan = new PersistenciaTapresca();
PersistenciaTamedico perTamedico = new PersistenciaTamedico();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos los datos del medico y del paciente
Paciente pac = (Paciente)sesion.getAttribute("PACIENTE");
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
int intEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
long intColectivo = pac.getTarjeta().getColectivo();
int intBeneficiario = pac.getTarjeta().getBeneficiario();
String modifiAuto = (String)request.getParameter("modifiAuto");
double dblPoliza = pac.getTarjeta().getPoliza();
int intOrden = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
//obtenemos el valor del campo param1 del medico conectado
//este valor se utiliza para calcular el numero de autorizacion para la prescripcion a realizar
int intParam1=perTamedico.obtenerValorParam1(intMedico);
//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);
//calculamos el numero de autorizacion para la prescripcion a realizar
long longAutorizacion = this.calcularCodigoAutorizacion(intMedico, intParam1);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
//Miramos si se trata de una modificación de la petición
if (modifiAuto.compareTo("")!=0 && (pertapresca_tarisan.existePeticion(Long.parseLong(modifiAuto)) && request.getParameter("listaCodigoElementosPrescripcion").length()>0)){
//Eliminamos la analítica
strSql = new StringBuffer();
strSql.append("delete from tapresca_tarisan");
strSql.append(" where AUTORIZACION = ?");
aCondiciones= new Object[1];
aCondiciones[0] = Long.parseLong(modifiAuto);
//LogTarisan.logger.log(NivelLog.DEBUG, "Eliminamos la analitica: "+Utilidades.obtenerSentenciaSQL(strSql, aCondiciones, null));
boolean resultadoAnaliticaEliminada = pertapresca_tarisan.eliminarPrescripcion(strSql.toString(), aCondiciones, conexion);
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[13];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(modifiAuto);
aValores[5] = Integer.valueOf(intEspecialidad);
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = (String)request.getParameter("centroPrescripcion");
aValores[10] = ""; //dejamos vacio el campo texto
aValores[12] = 5; //TIPO_PETICION = AUTORIZACION
if(pac.getDesplazado() == null)
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_propios);
if(pac.getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
{
aValores[11] = Integer.valueOf(pac.getTarjeta().getTarjeta());
}
else
{
aValores[11] = new String(pac.getTarjeta().getTarjetaDesplazado());
}
//recorremos los actos prescritos y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
StringTokenizer st = new StringTokenizer((String)request.getParameter("listaCodigoElementosPrescripcion"), "¬");
while (st.hasMoreTokens())
{
aValores[6] = Integer.valueOf( Integer.parseInt( st.nextToken() ) );
//actualizamos las prescriciones
pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
//actualizamos el valor de la primera visita en caso de que sea necesario
if ( ((String)request.getParameter("listaCodigoElementosPrescripcion")).indexOf("¬" + ParametrosConfiguracion.codigoPrimeraVisita + "¬") != -1 ) //se ha seleccionado el acto medico PRIMERA VISITA
{
int intCodActo=1;
actualizarPrimeraVisita(intMedico, intColectivo, dblPoliza, intBeneficiario, intCodActo, conexion);
}
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(modifiAuto));
//metemos el centro en la request para poder utilizarlo en la impresion
PersistenciaTacentro perTacentro= new PersistenciaTacentro();
request.setAttribute("centroImpresion", perTacentro.obtenerCentro( (String)request.getParameter("centroPrescripcion") ).getDescripcion() );
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
}else{
//Creamos la sentencia insert
strSql = new StringBuffer();
strSql.append("INSERT INTO tapresca_tarisan");
strSql.append(" (COLEC, POLIZA, ORDEN, PRESCRIPTOR, AUTORIZACION, ESPECIALIDAD, ACTO, FECHA, TEXTO, CENTRO, JUSTIFICACION, TARJETA, TIPO_PETICION)");
strSql.append(" VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");
//cargamos el array de valores con los datos fijos
aValores = new Object[13];
aValores[0] = Long.valueOf(intColectivo);
aValores[1] = Double.valueOf(dblPoliza);
aValores[2] = Integer.valueOf(intOrden);
aValores[3] = Integer.valueOf(intMedico);
aValores[4] = Long.valueOf(longAutorizacion);
aValores[5] = Integer.valueOf(intEspecialidad);
aValores[7] = dtFecha;
aValores[8] = (String)request.getParameter("informePrescripcion");
aValores[9] = (String)request.getParameter("centroPrescripcion");
aValores[10] = ""; //dejamos vacio el campo texto
aValores[12] = 5; //TIPO_PETICION = AUTORIZACION
if(pac.getDesplazado() == null)
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_propios);
if(pac.getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
{
aValores[11] = Integer.valueOf(pac.getTarjeta().getTarjeta());
}
else
{
aValores[11] = new String(pac.getTarjeta().getTarjetaDesplazado());
}
//recorremos los actos prescritos y para cada una de ellas insertanos un nuevo registro en la tabla tapresca_tarisan
String cadena = (String)request.getParameter("listaCodigoElementosPrescripcion");
//Aparece una  que no he conseguid averiguar de donde sale...
String limpio = cadena.replaceAll("Â","");
StringTokenizer st = new StringTokenizer(limpio, "¬");
while (st.hasMoreTokens())
{
aValores[6] = Integer.valueOf( Integer.parseInt( st.nextToken() ) );
//actualizamos las prescriciones
pertapresca_tarisan.insertarPrescripcion(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(intMedico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "tapresca_tarisan", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", conexion);
intUltimoValorCorrelativo++;
}
//actualizamos el valor del campo param1
strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(intMedico);
perTamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "Llegamos a la 3977");
//actualizamos el valor de la primera visita en caso de que sea necesario
if ( ((String)request.getParameter("listaCodigoElementosPrescripcion")).indexOf("¬" + ParametrosConfiguracion.codigoPrimeraVisita + "¬") != -1 ) //se ha seleccionado el acto medico PRIMERA VISITA
{
int intCodActo=1;
actualizarPrimeraVisita(intMedico, intColectivo, dblPoliza, intBeneficiario, intCodActo, conexion);
}
//metemos el codigo de autorizacon obtenido en la request para poder utilizarlo en la impresion
request.setAttribute("autorizacion", String.valueOf(longAutorizacion));
//metemos el centro en la request para poder utilizarlo en la impresion
PersistenciaTacentro perTacentro= new PersistenciaTacentro();
request.setAttribute("centroImpresion", perTacentro.obtenerCentro( (String)request.getParameter("centroPrescripcion") ).getDescripcion() );
//las actualizaciones han ido bien. Confirmamos la transaccion
ParametrosConfiguracion.dataStore.confirmarTransaccion(conexion);
LogTarisan.logger.log(NivelLog.DEBUG, "Llegamos a la 3996");
}
}
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 el historial del paciente con la información que el médico haya indicado.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
*/
private void actualizarHistoriaPaciente(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
Object[] aValores=null;
StringBuffer strSql;
try
{
PersistenciaTamovmpo perTamovmpo = new PersistenciaTamovmpo();
PersistenciaTareglog perTareglog = new PersistenciaTareglog();
//obtenemos los datos del medico y del paciente
int medico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
long colectivo = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo();
double poliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza();
int orden = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
//obtenemos el último valor del campo 'numero' para el medico conectado.
//este valor se utiliza para diferenciar registros de la tabla para el mismo médico y misma poliza
//a este numero se le sumara 1 para tener el valor del campo 'numero' a insertar
int intValorUltimoNumero=perTamovmpo.obtenerUltimoNumero(medico, colectivo, poliza, orden, fecha);
//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(medico, tsFechaUltimoAcceso);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
ParametrosConfiguracion.dataStore.iniciarTransaccion(conexion);
try
{
//Introducimos el nuevo registro en el historial del paciente
strSql = new StringBuffer();
strSql.append("INSERT INTO TAMOVMPO");
strSql.append(" (MEDICO, COLEC, POLIZA, ORDEN, FECHA, NUMERO, TEXTO)");
strSql.append(" VALUES (?,?,?,?,?,?,?)");
aValores = new Object[7];
aValores[0] = Integer.valueOf(medico);
aValores[1] = Long.valueOf(colectivo);
aValores[2] = Double.valueOf(poliza);
aValores[3] = Integer.valueOf(orden);
aValores[4] = fecha;
aValores[5] = Integer.valueOf(intValorUltimoNumero + 1);
aValores[6] = (String)request.getParameter("texto");
//actualizamos el historial del paciente
perTamovmpo.insertarMovimiento(strSql.toString(), aValores, conexion);
//insertamos un registro en la tabla tareglog para indicar los movimientos realizados por el usuario
perTareglog.insertarLog(medico, tsFechaUltimoAcceso, Calendar.getInstance(), intUltimoValorCorrelativo + 1, "TAMOVMPO", Utilidades.obtenerSentenciaSQL(strSql, aValores, null), "", 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 fecha de la primera visita, o en caso de no existir primera visita, inserta un nuevo registro para la primera visita.
* @param medico Código del médico.
* @param colectivo Número de colectico.
* @param poliza Código de la póliza.
* @param beneficiario Número de beneficiario.
* @param conexion Conexion por la que se actualiza el valor de la primera visita.
*/
private void actualizarPrimeraVisita(int medico, long colectivo, double poliza, int beneficiario, int acto, Connection conexion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql = new StringBuffer();
try
{
PersistenciaTaprimer perTaprimer = new PersistenciaTaprimer();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
java.sql.Date dtFechaPrimeraVisita = perTaprimer.obtenerFechaPrimeraVisita(medico, colectivo, poliza, beneficiario);
if (dtFechaPrimeraVisita==null) //no existe el registro de primera visita. Se añade uno nuevo
{
//Añadimos un nuevo registro en la tabla de taprimer como primera visita
strSql = new StringBuffer();
strSql.append("INSERT INTO TAPRIMER");
//strSql.append(" (MEDICO, COLEC, POLIZA, ORDEN, FECHA)");
strSql.append(" (MEDICO, COLEC, POLIZA, ORDEN, FECHA, ACTO)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?)");
aValores = new Object[6];
aValores[0] = Integer.valueOf(medico);
aValores[1] = Long.valueOf(colectivo);
aValores[2] = Double.valueOf(poliza);
aValores[3] = Integer.valueOf(beneficiario);
aValores[4] = dtFecha;
aValores[5] = Integer.valueOf(acto);
perTaprimer.insertarPrimeraVisita(strSql.toString(), aValores, conexion);
}
else //existe el registro de la primera visita. Se actualiza el valor de la fecha.
{
strSql = new StringBuffer();
strSql.append("UPDATE TAPRIMER");
strSql.append(" SET FECHA=?");
strSql.append(" WHERE MEDICO=?");
strSql.append(" AND COLEC=?");
strSql.append(" AND POLIZA=?");
strSql.append(" AND ORDEN=?");
strSql.append(" AND FECHA=?");
strSql.append(" AND ACTO=?");
aValores = new Object[1];
aValores[0] = dtFecha;
aCondiciones = new Object[6];
aCondiciones[0] = Integer.valueOf(medico);
aCondiciones[1] = Long.valueOf(colectivo);
aCondiciones[2] = Double.valueOf(poliza);
aCondiciones[3] = Integer.valueOf(beneficiario);
aCondiciones[4] = dtFechaPrimeraVisita;
aCondiciones[5] = Integer.valueOf(acto);
perTaprimer.modificarPrimeraVisita(strSql.toString(), aValores, aCondiciones, 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());
}
}
private void actualizarPrimeraLimpieza(int medico, long colectivo, double poliza, int beneficiario, int acto, Connection conexion) throws ExcepcionTarisan
{
Object[] aValores=null;
Object[] aCondiciones=null;
StringBuffer strSql = new StringBuffer();
try
{
PersistenciaTaprimer perTaprimer = new PersistenciaTaprimer();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
java.sql.Date dtFechaPrimeraLimpieza = perTaprimer.obtenerFechaPrimeraLimpieza(medico, colectivo, poliza, beneficiario);
if (dtFechaPrimeraLimpieza==null) //no existe el registro de primera limpieza. Se añade uno nuevo
{
//Añadimos un nuevo registro en la tabla de taprimer como primera limpieza
strSql = new StringBuffer();
strSql.append("INSERT INTO TAPRIMER");
strSql.append(" (MEDICO, COLEC, POLIZA, ORDEN, FECHA, ACTO)");
strSql.append(" VALUES (?, ?, ?, ?, ?, ?)");
aValores = new Object[6];
aValores[0] = Integer.valueOf(medico);
aValores[1] = Long.valueOf(colectivo);
aValores[2] = Double.valueOf(poliza);
aValores[3] = Integer.valueOf(beneficiario);
aValores[4] = dtFecha;
aValores[5] = Integer.valueOf(acto);
perTaprimer.insertarPrimeraLimpieza(strSql.toString(), aValores, conexion);
}
else //existe el registro de la primera limpieza. Se actualiza el valor de la fecha.
{
strSql = new StringBuffer();
strSql.append("UPDATE TAPRIMER");
strSql.append(" SET FECHA=?");
strSql.append(" WHERE MEDICO=?");
strSql.append(" AND COLEC=?");
strSql.append(" AND POLIZA=?");
strSql.append(" AND ORDEN=?");
strSql.append(" AND FECHA=?");
strSql.append(" AND ACTO=?");
aValores = new Object[1];
aValores[0] = dtFecha;
aCondiciones = new Object[6];
aCondiciones[0] = Integer.valueOf(medico);
aCondiciones[1] = Long.valueOf(colectivo);
aCondiciones[2] = Double.valueOf(poliza);
aCondiciones[3] = Integer.valueOf(beneficiario);
aCondiciones[4] = dtFechaPrimeraLimpieza;
aCondiciones[5] = Integer.valueOf(acto);
perTaprimer.modificarPrimeraLimpieza(strSql.toString(), aValores, aCondiciones, 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());
}
}
/**
* Valida las pistas de la Tarjeta del Paciente.
* @param request Objeto <code>HttpServletRequest</code> enviado por el cliente.
* @param response Objeto <code>HttpServletResponse</code> que retornará la página al cliente.
* @param sesion Objeto <code>HttpSession</code> con la sesión actual del usuario.
* @return true o false en función de la validación de la tarjeta.
*/
private boolean validarTarjeta(HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
String valorTarjeta = request.getParameter("TARJETA");
String troquelado = request.getParameter("TROQUELADO");
String troqueladoSinTarjeta = request.getParameter("TROQUELADO_SIN_TARJETA");
/**
* Hacer que la lectura de tarjeta identifique si es nuestra o de chipcard
* B80343100000000000194706=RIPA PEREZ JOSE JAVIER ^001100000811 --> 68 caracteres
* %803431000000000001947068=001000010811 --> 38 caracteres
* %01999000001659559701===========================046531=================0019470683157150199900001659559701 --> 105 caracteres
*/
int medico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
boolean resul = false;
String sMensaje = "";
boolean pista3 = false;
try
{
if(troqueladoSinTarjeta != null){ /* SE HA METIDO EL TROQUELADO PORQUE HA FALLADO EL PASO DE TARJETA */
if(ParametrosConfiguracion.log_control_medicos == 1)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a controlar el troquelado de las tarjetas de cada medico");
PersistenciaControlMedicosTroquelado perConMedTro = new PersistenciaControlMedicosTroquelado();
if(perConMedTro.insertar(medico, troqueladoSinTarjeta))
LogTarisan.logger.log(NivelLog.DEBUG, "Insercion del registro de control correcta (troquelado)");
}
Tarjeta tarjeta = new Tarjeta();
LogTarisan.logger.log(NivelLog.DEBUG, "El número del troquelado de la tarjeta es: " + troqueladoSinTarjeta);
tarjeta = this.parsearTarjeta_troquelado(troqueladoSinTarjeta);
LogTarisan.logger.log(NivelLog.DEBUG, "Se han cargado los datos bien. tarjeta: "+tarjeta.getTarjeta()+", contrato: "+tarjeta.getContrato()+", colectivo: "+tarjeta.getColectivo()+", poliza: "+tarjeta.getPoliza()+", orden"+tarjeta.getBeneficiario()+", entidad_chipcard: "+tarjeta.getEntidadChipcard()+"...");
tratarEntidades("",tarjeta, 0, sMensaje, sesion, request, response, resul, medico);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
else if(valorTarjeta != null)
{
if(ParametrosConfiguracion.log_control_medicos == 1)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a controlar las tarjetas de cada medico");
PersistenciaControlMedicos perConMed = new PersistenciaControlMedicos();
if(perConMed.insertar(medico, valorTarjeta))
LogTarisan.logger.log(NivelLog.DEBUG, "Insercion del registro de control correcta");
}
Tarjeta tarjeta = new Tarjeta();
int separador = 0;
separador = Utilidades.contar_coincidencias(valorTarjeta, "%");
PersistenciaTaDespla perTaDes = new PersistenciaTaDespla();
if(troquelado != null)
{
if(perTaDes.troquelado_repe(troquelado) || troquelado.length()<6)
{
LogTarisan.logger.log(NivelLog.ERROR, "El troquelado esta repetido...");
sMensaje = "Error, ha introducido un troquelado inválido,<br>por favor introduce el troquelado de la tarjeta actual.";
sesion.setAttribute("ERROR", sMensaje);
try {
response.sendRedirect("../jsp/error.jsp" );
return false;
} catch (IOException e) {
LogTarisan.logger.log(NivelLog.ERROR, "El troquelado esta repetido..."+e.toString());
}
}
}
if(valorTarjeta.substring(1, 6).compareTo(ParametrosConfiguracion.bin_redsa_asisa) == 0)
{
tarjeta = this.parsearTarjeta_redsa(valorTarjeta);
LogTarisan.logger.log(NivelLog.DEBUG, "REDSA ASISA: \n1.- Datos conseguidos: \n"+"Paciente.tarjeta.entidad="+tarjeta.getEntidadIMQ()+"\n"+"Paciente.tarjeta.contrato="+tarjeta.getContrato()+"\n");
}
else if(valorTarjeta.length()>30 && valorTarjeta.length()<50)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura de la pista 2");
tarjeta = this.parsearTarjeta_pista2(valorTarjeta);
//LogTarisan.logger.log(NivelLog.DEBUG, "Se ha cargado los datos bien. tarjeta: "+tarjeta.getTarjeta()+", contrato: "+tarjeta.getContrato()+", colectivo: "+tarjeta.getColectivo()+", poliza: "+tarjeta.getPoliza()+", orden"+tarjeta.getBeneficiario()+", entidad_chipcard: "+tarjeta.getEntidadChipcard()+"...");
}
else if (separador < 2)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Pistas: "+separador+"Lectura de la pista 3 - Médico: "+((Usuario)sesion.getAttribute("USUARIO")).getMedico());
sMensaje = "<font color='red'>Está usando un lector mal configurado... <br/>Préximamente dejará de funcionar<br/>Póngase en contacto con el departamento de informática. Gracias.</font>";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
if(valorTarjeta.charAt(46) == '=' && valorTarjeta.charAt(45) != '=')
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura de tarjetas \"chungas\" de sanitas y derivados. Caracter42: "+valorTarjeta.charAt(42));
//la tarjeta puede estar de la 39 a la 45 si en la posición 42 no hay un =
if(valorTarjeta.charAt(42) == '=')
{
LogTarisan.logger.log(NivelLog.DEBUG, "El número de tarjeta es 33-8: "+valorTarjeta.substring(33, 41));
tarjeta = this.parsearTarjeta_troquelado(valorTarjeta.substring(33, 41));
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "El número de tarjeta es 37-8: "+valorTarjeta.substring(37, 45));
tarjeta = this.parsearTarjeta_troquelado(valorTarjeta.substring(37,45));
}
}
else
{
sMensaje = "Está usando un lector mal configurado... Póngase en contacto con el departamento de informática. Gracias.";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
pista3=true;
/*tarjeta = this.parsearTarjeta_pista3(valorTarjeta.substring(valorTarjeta.length()-34));
tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);*/
}
}
else if (valorTarjeta.length()>50 && valorTarjeta.length()<80)
{
//hay algunas tarjetas que vienen sin el nombre en la pista uno y son más cortas aunque leamos las uno y dos:
// %B8034314600000001020%803431460000000002028235=006000011001%
if(Utilidades.contar_coincidencias(valorTarjeta, "%") >= 2)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura de la pistas 1 y 2 pero de las cortas- "+valorTarjeta.substring(1, 8));
String[] pistas = valorTarjeta.split("%");
String pista2 = pistas[2];
LogTarisan.logger.log(NivelLog.DEBUG, "Pista2 vale: "+pista2);
//Le añadimos un espacio delante por que las otras tarjetas llevan un = y empezamos la comprobación del lun desde el segundo caracter
tarjeta = this.parsearTarjeta_pista2(" "+pista2);
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura de la pista 1 - "+valorTarjeta.substring(1, 8));
tarjeta = this.parsearTarjeta_pista1(valorTarjeta);
}
}
else if(valorTarjeta.length()>96)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura de las pistas 1 y 2");
if(valorTarjeta.charAt(46) == '=')
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura de tarjetas \"chungas\" de sanitas y derivados. Caracter42: "+valorTarjeta.charAt(42));
//la tarjeta puede estar de la 39 a la 45 si en la posición 42 no hay un =
if(valorTarjeta.charAt(42) == '=')
{
LogTarisan.logger.log(NivelLog.DEBUG, "El número de tarjeta es 33-8: "+valorTarjeta.substring(33, 41));
tarjeta = this.parsearTarjeta_troquelado(valorTarjeta.substring(33, 41));
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "El número de tarjeta es 37-8: "+valorTarjeta.substring(37, 45));
tarjeta = this.parsearTarjeta_troquelado(valorTarjeta.substring(37,45));
}
}
else if (valorTarjeta.substring(1, 6).compareTo(ParametrosConfiguracion.bin_redsa_asisa) != 0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "valorTarjeta.substring(2,8)->"+valorTarjeta.substring(2,8));
tarjeta = this.parsearTarjeta_pistas1_2(valorTarjeta);
}
}
/*else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Lectura manual del número de tarjeta: ATS"+(String)sesion.getAttribute("PERFIL"));
String perfil = (String)sesion.getAttribute("PERFIL");
if(perfil.compareTo(Constantes.PERFIL_ATS) == 0)
tarjeta = this.parsearTarjeta_troquelado(valorTarjeta);
}*/
if (!pista3){
tratarEntidades(valorTarjeta, tarjeta, separador, sMensaje, sesion, request, response, resul, medico);
}
}
else
{
sMensaje = "Tarjeta de paciente inválida";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
}
catch(ExcepcionTarisan ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion en el paso de tarjeta " + valorTarjeta + " (" + ex + ")");
throw ex;
}
catch(Exception ex)
{
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion en el paso de tarjeta " + valorTarjeta + " (" + ex + ")");
throw new ExcepcionTarisan(ex.getMessage());
}
return resul;
}
private Paciente parsearDesplazado_pistas1_2(String valorTarjeta)
{
Paciente pac = new Paciente();
String asegurado = "";
StringTokenizer st = new StringTokenizer(valorTarjeta, "%");
int iteracion = 0;
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a parsear un desplazado leyendo las pistas 1 y 2 de la tarjeta");
while (st.hasMoreTokens())
{
String strtarjeta = st.nextToken() ;
//lectura 1 pista
iteracion = iteracion +1;
if(iteracion == 1)
{
//LogTarisan.logger.log(NivelLog.DEBUG, "\n\n\nempieza por: "+strtarjeta.substring(0, 5)+"--> "+ParametrosConfiguracion.bin_chipcard_sanitas+"\n\n\n");
/*if((strtarjeta.substring(0, 5).compareTo(ParametrosConfiguracion.bin_redsa_asisa) == 0) || (strtarjeta.substring(1, 7).compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0))
{
asegurado = nombre_asegurado_falta_letra(valorTarjeta);
//asegurado = valorTarjeta.substring(19, 45);
pac.setNombre(asegurado);
}
else if(strtarjeta.substring(0, 6).compareTo("846101") == 0) //strtarjeta.length()>50 && strtarjeta.length()<80)
{
//
/*
* Tarjeta adeslas:
* %B80344600000006631936500=M. SOLEDAD DORADO PORTELA =611012120606%803446000000066319365006=611121200000%
* %B80344600000003140007400=MARIA GARCIA CALAVIA =824080121401%803446000000031400074006=824801201401%
*
asegurado = nombre_asegurado_falta_letra(valorTarjeta);
//asegurado = strtarjeta.substring(25, 55);
pac.setNombre(asegurado);
}*/
if((strtarjeta.indexOf('Â')+strtarjeta.indexOf('Ê')+strtarjeta.indexOf('Î')+strtarjeta.indexOf('Ô')+strtarjeta.indexOf('Û'))>0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta con la lectura con cejilla ^ en alguna vocal");
asegurado = nombre_asegurado_falta_letra(valorTarjeta);
}
else if (strtarjeta.substring(0, 5).compareTo(ParametrosConfiguracion.bin_redsa_asisa) == 0)
{
asegurado = nombre_asegurado_falta_letra(valorTarjeta);
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_sanitas)==0)
{
asegurado = valorTarjeta.substring(25, 54).trim();
}
else // if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
{
//asegurado = nombre_asegurado_falta_letra(valorTarjeta);
asegurado = valorTarjeta.substring(26, 55).trim();
}
pac.setNombre(asegurado);
}
if(iteracion == 2)
{
//lectura de la segunda pista:
LogTarisan.logger.log(NivelLog.DEBUG, "Leyendo la pista2: contrato = "+Integer.parseInt(strtarjeta.substring(strtarjeta.indexOf("=")+1, strtarjeta.indexOf('=')+4)));
Tarjeta tar = new Tarjeta();
tar.setPista2(strtarjeta);
if(strtarjeta.indexOf("=")>0)
{
tar.setTarjetaDesplazado(strtarjeta.substring(0, strtarjeta.indexOf("=")));
tar.setContrato(Integer.parseInt(strtarjeta.substring(strtarjeta.indexOf("=")+1, strtarjeta.indexOf('=')+4)));
LogTarisan.logger.log(NivelLog.DEBUG, "Contrato obtenido: "+tar.getContrato());
}
else
{
tar.setTarjetaDesplazado(strtarjeta.substring(0, strtarjeta.indexOf("")));
tar.setContrato(Integer.parseInt(strtarjeta.substring(strtarjeta.indexOf("")+1, strtarjeta.indexOf('')+4)));
}
PersistenciaTabenefi aux = new PersistenciaTabenefi();
if(aux.existeTarjetaChipcard(tar.getTarjetaDesplazado(),0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "Como existeTarjetaChipcard la asigno");
int contrato = tar.getContrato();
tar = aux.generarObjetoTarjetaChipcard(tar.getTarjetaDesplazado(),0);
tar.setContrato(contrato);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignada correctamente");
}
else
{
tar.setPoliza(0);
}
LogTarisan.logger.log(NivelLog.DEBUG, "Asigno la tarjeta al paciente"+tar.getPista2()+"\n\n");
//LogTarisan.logger.log(NivelLog.DEBUG, "Entidad Chipcard: " + strtarjeta.substring(0, 6) + " y asisa es: " + ParametrosConfiguracion.bin_chipcard_adeslas);
if (strtarjeta.substring(0, 4).compareTo(ParametrosConfiguracion.bin_redsa_asisa.substring(1)) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_redsa_asisa);
tar.setEntidadIMQ(4);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 4 a las tarjetas de Asisa");
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_adeslas);
tar.setEntidadIMQ(3);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 3 a las tarjetas de Adeslas");
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_imqbilbo);
tar.setEntidadIMQ(3);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 3 a las tarjetas de IMQBilbao");
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);
tar.setEntidadIMQ(0);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 0 a las tarjetas Propias");
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_dkv) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_dkv);
tar.setEntidadIMQ(32);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 32 a las tarjetas de DKV");
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
tar.setEntidadIMQ(5);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 5 a las tarjetas de sanitas");
}
else if (strtarjeta.substring(0, 6).compareTo(ParametrosConfiguracion.bin_chipcard_hna) == 0)
{
tar.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_hna);
tar.setEntidadIMQ(58);
LogTarisan.logger.log(NivelLog.DEBUG, "Asignamos la entidad 58 a las tarjetas de hna-antares");
}
/*
* if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
entidad=3;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_dkv) == 0)
entidad=32;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
entidad=5;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0)
entidad=3;
//entidad=7;
else if(entidadChipcard.compareToIgnoreCase(ParametrosConfiguracion.bin_redsa_asisa)==0)
entidad=4;
*/
//PersistenciaTabenefi perta = new PersistenciaTabenefi();
//pac.setFechaBaja(perta.getFechaBaja(strtarjeta.substring(0, strtarjeta.indexOf('='))));
LogTarisan.logger.log(NivelLog.DEBUG, "Justo antes de asignar la tarjeta al asegurado el contrato es: "+tar.getContrato());
tar.setEstadeBaja(false);
pac.setFechaBaja(null);
pac.setTarjeta(tar);
pac.setDesplazado(tar.getEntidadChipcard());
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Devuelvo el paciente con entidad Paciente.tarjeta.entidad: " + pac.getTarjeta().getEntidadIMQ()+" - "+pac.getTarjeta().getColectivo()+" - "+pac.getTarjeta().getPoliza()+" - "+pac.getTarjeta().getBeneficiario()+" ->"+pac.getTarjeta().getPista2());
pac.set_noesiguala_inactivar(true);
return pac;
}
/**
* Hay lectores que leen las tarjetas de forma rara y le asignan el caracter separador a la primera letra del nombre del asegurado:
* %B80344400051885104804440ISMAEL AIBAR NOTARIO ^186160121301%803444000518851048044402=186601210000%
* ^
* en lugar de leer
* %B80344400051885104804440^ISMAEL AIBAR NOTARIO ^186160121301%803444000518851048044402=186601210000%
* %B8461010071554411^POSSO DE CAICEDO MARIA HE^2210%8461010071554411=22101210%
* @param valorTarjeta lo que lee el lector
* @return el nombre del asegurado con la primera letra bien corregida.
*/
private String nombre_asegurado_falta_letra(String valorTarjeta)
{
String resul="";
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta leida: "+valorTarjeta);
if(valorTarjeta.contains("^"))
{
if(valorTarjeta.indexOf("^") == 55)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Se encuentra la ^. en la posicion 25 hay: " + valorTarjeta.charAt(25));
// String posicion = valorTarjeta.charAt(25)+"";
/*
* uso ifs por que le switch no funciona para strings/chars hasta la versión 1.7 de java
*/
if (valorTarjeta.charAt(25) == 'Â')
{
resul = "A"+valorTarjeta.substring(26, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la A -> "+resul);
}
else if (valorTarjeta.charAt(25) == 'Ê')
{
resul = "E"+valorTarjeta.substring(26, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la E -> "+resul);
}
else if (valorTarjeta.charAt(25) == 'Î')
{
resul = "I"+valorTarjeta.substring(26, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la I -> "+resul);
}
else if (valorTarjeta.charAt(25) == 'Ô')
{
resul = "O"+valorTarjeta.substring(26, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la O -> "+resul);
}
else if (valorTarjeta.charAt(25) == 'Û')
{
resul = "U"+valorTarjeta.substring(26, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la U -> "+resul);
}
}
else
{
if(valorTarjeta.charAt(18)== 'Â')
{
resul = "A"+valorTarjeta.substring(19, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la A -> "+resul);
}
else if(valorTarjeta.charAt(18)== 'Ê')
{
resul = "E"+valorTarjeta.substring(19, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la E -> "+resul);
}
else if(valorTarjeta.charAt(18)== 'Î')
{
resul = "I"+valorTarjeta.substring(19, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la I -> "+resul);
}
else if(valorTarjeta.charAt(18)== 'Ô')
{
resul = "O"+valorTarjeta.substring(19, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la O -> "+resul);
}
else if(valorTarjeta.charAt(18)== 'Û')
{
resul = "U"+valorTarjeta.substring(19, valorTarjeta.indexOf("^"));
LogTarisan.logger.log(NivelLog.DEBUG, "Es la U -> "+resul);
}
else if(valorTarjeta.charAt(18) == '^')
{
int fin = valorTarjeta.indexOf('^', 20);
resul = valorTarjeta.substring(19, fin);
LogTarisan.logger.log(NivelLog.DEBUG, "Nombre: "+resul);
}
else
{
resul = valorTarjeta.substring(26, 55).trim();
}
}
}
return resul.trim();
}
//private Tarjeta parsearTarjeta_pistas1_2(String valorTarjeta) throws ExcepcionTarisan
public static Tarjeta parsearTarjeta_pistas1_2(String valorTarjeta) throws ExcepcionTarisan
{
//%B80343100000000000194706=RIPA PEREZ JOSE JAVIER ^001100000811%803431000000000001947068=001000010811%
Tarjeta tarjeta = new Tarjeta();
tarjeta.setValida(false);
StringTokenizer st = new StringTokenizer(valorTarjeta, "%");
String entidad = "";
while (st.hasMoreTokens())
{
//obtenemos los String correspondientes a cada pista
String strtarjeta = st.nextToken() ;
boolean desplazado = false;
if(strtarjeta.length()>50 && strtarjeta.length()<80)
{
//Pista1
LogTarisan.logger.log(NivelLog.DEBUG, "Pista 1: "+strtarjeta);
//803431 --> DIRECTOS IMQ
/*
* La entidad a la que pertenece la tarjeta:
* 0 -> IMQ DIRECTOS
* 1 -> ADESLAS
* 2 -> DKV
* 3 -> SANITAS
* 4 -> ERROR!!
* 58 -> ANTARES
*/
if(strtarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);
entidad = ParametrosConfiguracion.bin_chipcard_propios;
desplazado = false;
}
else if(strtarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_dkv) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_dkv);
entidad = ParametrosConfiguracion.bin_chipcard_dkv;
desplazado = true;
}
else if(strtarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_adeslas);
entidad = ParametrosConfiguracion.bin_chipcard_adeslas;
desplazado = true;
}
else if(strtarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
entidad = ParametrosConfiguracion.bin_chipcard_sanitas;
desplazado = true;
}
else if(strtarjeta.substring(0,6).compareTo(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
entidad = ParametrosConfiguracion.bin_chipcard_sanitas;
desplazado = true;
}
else if(strtarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
entidad = ParametrosConfiguracion.bin_chipcard_imqbilbo;
desplazado = true;
}
/*else if(strtarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_hna) == 0)*/
else if(strtarjeta.substring(1,7).compareTo("803497") == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
//throw new ExcepcionTarisan("Error! La tarjeta es de una entidad con la que no tenemos acuerdo"); /*El 17/02/2016 llama Daniel Cámara diciendo que se excluyan de Tarisan las tarjetas de antares */
throw new ExcepcionTarisan("Error! La facturación de las tarjetas de HNA/ANTARES debe hacerse de forma manual");
/*entidad = ParametrosConfiguracion.bin_chipcard_hna;
desplazado = true;*/
}
else
{
LogTarisan.logger.log(NivelLog.ERROR, "Error! La tarjeta es de una entidad con la que no tenemos acuerdo");
/*throw new ExcepcionTarisan("Error! La tarjeta es de una entidad con la que no tenemos acuerdo");*/
}
}
else
{
//Pista2
LogTarisan.logger.log(NivelLog.DEBUG, "Pista 2: "+strtarjeta);
//tarjeta = this.parsearTarjeta_pista2("%"+strtarjeta);
tarjeta = parsearTarjeta_pista2("%"+strtarjeta);
tarjeta.setTarjetaDesplazado(strtarjeta.substring(0, 24));
tarjeta.setPista2(strtarjeta);
LogTarisan.logger.log(NivelLog.DEBUG, "La tarjeta es de la entidad: "+tarjeta.getEntidadChipcard());
if(entidad == "")
entidad = tarjeta.getEntidadChipcard();
//
/*%B80343611111100002222203^TARJETA PRUSANITAS ^502120126811%803436111111000022222031=502201216811%
* Hay que leer el contrato chipcard en la pista dos, son los 3 dígitos que vienen después del =
* y tambión la fecha de alta que viene en los últimos 4 dígitos de la pista 2
* No nos interesa la fecha de alta de la tarjeta, ponemos la fecha de hoy
*/
//LogTarisan.logger.log(NivelLog.DEBUG, "Contrato de la pista 2: "+strtarjeta.substring(strtarjeta.indexOf("=")+1, strtarjeta.indexOf('=')+4));
//tarjeta.setContrato(Integer.parseInt(strtarjeta.substring(strtarjeta.indexOf("=")+1, strtarjeta.indexOf('=')+4)));
Calendar fecha = Calendar.getInstance();
String fecha_alta = "";
fecha_alta = String.valueOf(fecha.get(Calendar.MONTH)+1);
if(fecha_alta.length()<2)
fecha_alta = "0"+fecha_alta;
fecha_alta = fecha_alta + String.valueOf(fecha.get(Calendar.YEAR)).substring(2);
tarjeta.setFecha_Alta_Chipcard(fecha_alta);
}
}
tarjeta.setEntidadChipcard(entidad);
LogTarisan.logger.log(NivelLog.DEBUG, "Entidad: " + tarjeta.getEntidadChipcard());
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta: "+tarjeta.getTarjeta());
return tarjeta;
}
private Tarjeta parsearTarjeta_troquelado(String valorTarjeta) throws ExcepcionTarisan
{
//0019470683150465
Tarjeta tarjeta = new Tarjeta();
tarjeta.setValida(false);
try
{
PersistenciaTabenefi pertabenefi = new PersistenciaTabenefi();
tarjeta = pertabenefi.generarObjetoTarjeta(Integer.parseInt(valorTarjeta.substring(0, 8)));
tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);
}
catch(Exception ex)
{
throw new ExcepcionTarisan(ex.toString());
}
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n\nValor tarjeta: "+tarjeta.getTarjeta());
tarjeta.setValida(true);
return tarjeta;
}
private Tarjeta parsearTarjeta_redsa(String valorTarjeta) throws ExcepcionTarisan
{
Tarjeta resultado = new Tarjeta();
/*
* vamos a buscar en ttbenefi si existe la tarjeta_chipcard para obtener col, pol, orden
*/
PersistenciaTabenefi per = new PersistenciaTabenefi();
resultado = per.generarObjetoTarjetaChipcard(valorTarjeta.substring(2,18), 0);
resultado.setValida(true);
resultado.setEntidadChipcard(ParametrosConfiguracion.bin_redsa_asisa);
resultado.setTarjetaDesplazado(valorTarjeta.substring(2, 18));
Calendar fecha = Calendar.getInstance();
String fecha_alta = "";
fecha_alta = String.valueOf(fecha.get(Calendar.MONTH)+1);
if(fecha_alta.length()<2)
fecha_alta = "0"+fecha_alta;
fecha_alta = fecha_alta + String.valueOf(fecha.get(Calendar.YEAR)).substring(2);
resultado.setFecha_Alta_Chipcard(fecha_alta);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n\nVamos a buscar col,pol,ord de la tar asisa: "+valorTarjeta);
/* ya hemos parseado la tarjeta no hace falta volverlo a hacer */
//Paciente temporal = parsearDesplazado_pistas1_2(valorTarjeta);
//Tarjeta aux = temporal.getTarjeta();
//resultado.setContrato(aux.getContrato());
LogTarisan.logger.log(NivelLog.DEBUG, "Contrato = "+resultado.getContrato());
//resultado.setEntidadIMQ(4);
//resultado.setFecha_Alta_Chipcard(fecha_alta);
return resultado;
}
private Tarjeta parsearTarjeta_pista1(String valorTarjeta) throws ExcepcionTarisan
{
//%B80343100000000000194706=RIPA PEREZ JOSE JAVIER ^001100000811
Tarjeta tarjeta = new Tarjeta();
tarjeta.setValida(false);
try
{
PersistenciaTabenefi pertabenefi = new PersistenciaTabenefi();
tarjeta = pertabenefi.generarObjetoTarjeta(Integer.parseInt(valorTarjeta.substring(15, 25)));
if(tarjeta.getValida())
tarjeta.setTarjetaDesplazado(valorTarjeta.substring(2,25));
String entidad = "0";
if(valorTarjeta.substring(2,8).compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);
entidad = ParametrosConfiguracion.bin_chipcard_propios;
}
else if(valorTarjeta.substring(2,8).compareTo(ParametrosConfiguracion.bin_chipcard_dkv) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_dkv);
entidad = ParametrosConfiguracion.bin_chipcard_dkv;
}
else if(valorTarjeta.substring(2,8).compareTo(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_adeslas);
entidad = ParametrosConfiguracion.bin_chipcard_adeslas;
}
else if(valorTarjeta.substring(2,8).compareTo(ParametrosConfiguracion.bin_chipcard_sanitas) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
entidad = ParametrosConfiguracion.bin_chipcard_sanitas;
}
else if(valorTarjeta.substring(2,8).compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0)
{
//tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_sanitas);
entidad = ParametrosConfiguracion.bin_chipcard_imqbilbo;
}
else
{
//throw new ExcepcionTarisan("Error! La tarjeta es de una entidad con la que no tenemos acuerdo");
LogTarisan.logger.log(NivelLog.ERROR, "Error! La tarjeta es de una entidad con la que no tenemos acuerdo");
}
tarjeta.setEntidadChipcard(entidad);
/*
* al leer solo la pista 1 no tenemos el luhn así que si llega hasta aquí calculamos el luhn válido para poder meter el dato completo en tamovext
* he detectado que alguna tarjeta consigue provocar un bucle infinito, añado un contador para que no haga más de 11 intentos
*/
int luhn = 0;
int cont=1;
boolean seguir = false;
while(!seguir && cont<11){
cont+=1;
seguir = Utilidades.calcularLuhn(valorTarjeta.substring(2,25)+luhn);
if(!seguir)
luhn+=1;
}
if(tarjeta.getValida())
tarjeta.setTarjetaDesplazado(valorTarjeta.substring(2,25)+luhn);
LogTarisan.logger.log(NivelLog.DEBUG, "Pista 1: Valor Tarjeta: "+tarjeta.getTarjeta());
}
catch(Exception ex)
{
throw new ExcepcionTarisan(ex.toString());
}
return tarjeta;
}
private boolean tratarEntidades(String valorTarjeta,Tarjeta tarjeta, Integer separador, String sMensaje, HttpSession sesion, HttpServletRequest request, HttpServletResponse response, boolean resul, Integer medico) throws ExcepcionTarisan{
try{
int intMedico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
LogTarisan.logger.log(NivelLog.DEBUG, "Se han cargado los datos bien. tarjeta: "+tarjeta.getTarjeta()+", contrato: "+tarjeta.getContrato()+", colectivo: "+tarjeta.getColectivo()+", poliza: "+tarjeta.getPoliza()+", orden"+tarjeta.getBeneficiario()+", entidad_chipcard: "+tarjeta.getEntidadChipcard()+"...");
// comprobamos si la poliza es una de las igualas del medico
if(tarjeta.getValida() && tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_propios)==0)
{
PersistenciaPaciente per = new PersistenciaPaciente();
Object objetoSeleccionado = null;
try
{
//objetoSeleccionado = per.seleccionar(tarjeta, ((Usuario)sesion.getAttribute("USUARIO")).getMedico());
//-> peta aqui
objetoSeleccionado = per.seleccionarColPolOrd(tarjeta, ((Usuario)sesion.getAttribute("USUARIO")).getMedico());
Paciente paciente = (Paciente)objetoSeleccionado;
LogTarisan.logger.log(NivelLog.INFO, "Tarjeta de paciente válida: " + tarjeta);
LogTarisan.logger.log(NivelLog.INFO, "Paciente: " + paciente.getNombre());
paciente.setDesplazado(ParametrosConfiguracion.bin_chipcard_propios);
String strPerfil = (String)sesion.getAttribute("PERFIL");
LogTarisan.logger.log(NivelLog.DEBUG, "Comprobar si esta autorizado" + paciente.getAutorizado().trim().toUpperCase());
LogTarisan.logger.log(NivelLog.DEBUG, "Comprobar si el bin de chipcard es propio o desplazado.");
PersistenciaTapolfac perTapolfac = new PersistenciaTapolfac();
// añadir a la sesion del paciente si es igualadel medico o no para no permitir hacer nada al médico de cabecera con pacientes que no son suyos
/*
* Siguiendo el ticket https://incidencias.imqnavarra.com/soporte/scp/tickets.php?id=52142 se cambia el comportamiento para los
* mutualistas. Siempre podrán ir a cualquier médico de cabecera.
* Modificar la función perTapolfac.esPolizaIgualaMedico para que si es mutualista devuelva siempre un 0 para que le deje
*/
/*Integer blnEsPolizaIgualaMedico = perTapolfac.esPolizaIgualaMedico(((Usuario)sesion.getAttribute("USUARIO")).getMedico(), paciente.getTarjeta().getColectivo(), paciente.getTarjeta().getPoliza());*/
int blnEsPolizaIgualaMedico = perTapolfac.esPolizaIgualaMedico(((Usuario)sesion.getAttribute("USUARIO")).getMedico(), paciente.getTarjeta().getColectivo(), paciente.getTarjeta().getPoliza());
LogTarisan.logger.log(NivelLog.DEBUG, "Comprobamos si es igualado. Para añadir al paciente en sesion. "+blnEsPolizaIgualaMedico);
boolean activo = true;
if(blnEsPolizaIgualaMedico == 2 && ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad() == 1)
{
LogTarisan.logger.log(NivelLog.DEBUG, "El médico de sesion es de cabecera y el paciente no es igualado suyo.");
activo = false;
}
else if(blnEsPolizaIgualaMedico == 1)
LogTarisan.logger.log(NivelLog.DEBUG, "El médico de sesion es de cabecera y el paciente es igualado suyo.");
else
LogTarisan.logger.log(NivelLog.DEBUG, "O el médico no es de cabecera.");
paciente.set_noesiguala_inactivar(activo);
sesion.setAttribute("PACIENTE", paciente);
if (paciente.getAutorizado().trim().toUpperCase().compareTo("S") == 0 || (!strPerfil.equalsIgnoreCase(Constantes.PERFIL_ANALISTA) /*&& !strPerfil.equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)*/))
{
//se trata de un analista. se le redirecciona a la pagina de analista
if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA) ) {
//se comprueba si el paciente ha pasado una tarjeta dental en vez de una de salud
if(Utilidades.buscar_en_properties(""+tarjeta.getContrato(), ParametrosConfiguracion.contrato_dental))
//Se ha pasado una tarjeta dental para acceder a un especialista.
//Se redirige a gestor.jsp para que utilice una de salud
{
sMensaje = "<h3>HA PASADO UNA TARJETA DENTAL. PARA ACCEDER AL ESPECIALISTA DEBE UTILIZAR UNA TARJETA DE SALUD</h3>";
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n Ha pasado una tarjeta dental para acceder a un especialista. Volvemos a gestor.jsp");
response.sendRedirect("../jsp/pac/gestor.jsp");
return resul = false;
}else{
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
}
//se trata de un radiologo. se le redirecciona a la pagina de radiologo
else if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO) ) {
//se comprueba si el paciente ha pasado una tarjeta dental en vez de una de salud
if(Utilidades.buscar_en_properties(""+tarjeta.getContrato(), ParametrosConfiguracion.contrato_dental))
//Se ha pasado una tarjeta dental para acceder a un especialista.
//Se redirige a gestor.jsp para que utilice una de salud
{
sMensaje = "<h3>HA PASADO UNA TARJETA DENTAL. PARA ACCEDER AL ESPECIALISTA DEBE UTILIZAR UNA TARJETA DE SALUD</h3>";
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n Ha pasado una tarjeta dental para acceder a un especialista. Volvemos a gestor.jsp");
response.sendRedirect("../jsp/pac/gestor.jsp");
return resul = false;
}else{
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
{
//se comprueba si el paciente ha pasado una tarjeta dental en vez de una de salud
if(Utilidades.buscar_en_properties(""+tarjeta.getContrato(), ParametrosConfiguracion.contrato_dental))
//Se ha pasado una tarjeta dental para acceder a un especialista.
//Se redirige a gestor.jsp para que utilice una de salud
{
sMensaje = "<h3>HA PASADO UNA TARJETA DENTAL. PARA ACCEDER AL ESPECIALISTA DEBE UTILIZAR UNA TARJETA DE SALUD</h3>";
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n Ha pasado una tarjeta dental para acceder a un especialista. Volvemos a gestor.jsp");
response.sendRedirect("../jsp/pac/gestor.jsp");
return resul = false;
}else{
//se trata de un podólogo, ats, logopeda o de rehabilitación, hay que verificar que tiene autorización activa.
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
}
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA))
{
//se trata de un dentista, hay que ver si está usando una tarjeta dental, si tiene dental, o si siendo de salud tiene cobertura dental.
//tarjeta.getContrato() --> 723 (Dental),
LogTarisan.logger.log(NivelLog.DEBUG, "Perfil Odontologo");
if(Utilidades.buscar_en_properties(""+tarjeta.getContrato(), ParametrosConfiguracion.contrato_dental))
{
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
}
else
//Paciente con tarjeta de salud.
if (per.tieneDental(paciente.getTarjeta().getTarjetaDesplazado(), medico)){
//El paciente ha pasado una tarjeta de salud pero TIENE TARJETA DENTAL.
sMensaje = "<h3>EL PACIENTE TIENE TARJETA DENTAL, DEBE UTILIZARLA</h3>";
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n Tiene tarjeta dental. Volvemos a gestor.jsp");
response.sendRedirect("../jsp/pac/gestor.jsp");
}else if (tarjeta.getContrato() == ParametrosConfiguracion.salud_con_cobertura_dental){
//El paciente no tiene tarjeta dental pero su TARJETA DE SALUD TIENE COBERTURA DENTAL
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
}else{
//Paciente SIN TARJETA NI COBERTURA DENTAL
//response.sendRedirect("../jsp/pac/franquicias_dentales.jsp" );
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
}
{
}
}
/*se trata de un especialista o de un medico de cabecera. Se le redirecciona a la pagina de facturacion.
else if ( ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA) ) {
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=0&pagina=1");
}*/
else
{
int compatible = especialidadCompatible(paciente, Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad() ));
//se comprueba si el paciente ha pasado una tarjeta dental en vez de una de salud
if(Utilidades.buscar_en_properties(""+tarjeta.getContrato(), ParametrosConfiguracion.contrato_dental))
//Se ha pasado una tarjeta dental para acceder a un especialista.
//Se redirige a gestor.jsp para que utilice una de salud
{
sMensaje = "<h3>HA PASADO UNA TARJETA DENTAL. PARA ACCEDER AL ESPECIALISTA DEBE UTILIZAR UNA TARJETA DE SALUD</h3>";
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n Ha pasado una tarjeta dental para acceder a un especialista. Volvemos a gestor.jsp");
response.sendRedirect("../jsp/pac/gestor.jsp");
return resul = false;
}
//se comprueba si el sexo del paciente es compatible con el de la especialidad
else if( compatible == 1)
{
response.sendRedirect("../jsp/pac/facturacion.jsp?x=0&pagina=1");
}
else
{
if (compatible == 2)
sMensaje = "El sexo del paciente no es compatible con la especialidad del médico.";
if (compatible ==3)
sMensaje = "El paciente tiene m&aacute;s de 14 a&ntilde;os ya no tiene derecho a pediatr&iacute;a";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
}
}
else
{
LogTarisan.logger.log(NivelLog.INFO, "El beneficiario no ha firmado la autorización");
//se comprueba si el paciente ha pasado una tarjeta dental en vez de una de salud
if(Utilidades.buscar_en_properties(""+tarjeta.getContrato(), ParametrosConfiguracion.contrato_dental))
//Se ha pasado una tarjeta dental para acceder a un especialista.
//Se redirige a gestor.jsp para que utilice una de salud
{
sMensaje = "<h3>HA PASADO UNA TARJETA DENTAL. PARA ACCEDER AL ESPECIALISTA DEBE UTILIZAR UNA TARJETA DE SALUD</h3>";
sesion.setAttribute("ERROR", sMensaje);
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n Ha pasado una tarjeta dental para acceder a un especialista. Volvemos a gestor.jsp");
response.sendRedirect("../jsp/pac/gestor.jsp");
return resul = false;
}else{
sMensaje = "El beneficiario no ha firmado la autorizaci&oacute;n";
response.sendRedirect("../jsp/pac/firma_autorizacion.jsp");
}
}
}
catch(ClassCastException ex)
{
Integer nMensaje = (Integer)objetoSeleccionado;
sMensaje = this.obtenerMensaje(nMensaje);
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
}
resul = true;
}
/*
* hay que comprobar en el campo identificador de ttbenefi si el asegurado tiene asignado un valor
* si lo tiene seguimos igual que siempre, si no lo tiene hay que recargar la página gestor
* pasándole la lectura de la tarjeta y el parámetro embosado=1 para que solicite el valor
*/
else if(tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_adeslas)==0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta de adeslas");
//Verificamos si en ttbenefi tiene identificador:
PersistenciaTabenefi pertaben = new PersistenciaTabenefi();
boolean tiene_embosado = pertaben.tiene_embosado(tarjeta.getTarjetaDesplazado());
LogTarisan.logger.log(NivelLog.DEBUG, "ADESLAS: tiene embosado?"+tiene_embosado+", tiene parametro troquelado?"+request.getParameter("TROQUELADO"));
if(!tiene_embosado && (request.getParameter("TROQUELADO") != null) && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
String pista2 = pac.getTarjeta().getPista2();
tarjeta.setPista2(pista2);
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(3);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_adeslas);
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
/*if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}else{*/
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
tades.setTroquelado(pac.getIdentificador());
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
// }
}
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado no esta casado y no puede acceder al analista");
sMensaje = "Este desplazado todavía no puede acceder a los servicios del anlaista";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
/*else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
}*/
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
}
else if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de adeslas no tiene embosado y no esta casado.\n");
response.sendRedirect("../jsp/pac/gestor.jsp?embosado=1");
resul = true;
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de adeslas tiene embosado o ya esta casada.\n");
//Aceptamos las tarjetas de adeslas:
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
String pista2 = pac.getTarjeta().getPista2();
tarjeta.setPista2(pista2);
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(3);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_adeslas);
}/*else if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(pac.getTarjeta().getEntidadIMQ());
tades.setContrato(pac.getTarjeta().getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}*/
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_adeslas);
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(pac.getTarjeta().getEntidadIMQ());
tades.setContrato(pac.getTarjeta().getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
/*else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
}*/
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
//Fin aceptamos las tarjetas de adeslas
}
/*
//No se aceptan tarjetas "ajenas
sMensaje = "La tarjeta no es de IMQ Navarra - Operativa no desarrollada<br/>Usar bacaladera";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
*/
}
else if(tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_hna)==0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta de hna");
//Verificamos si en ttbenefi tiene identificador:
PersistenciaTabenefi pertaben = new PersistenciaTabenefi();
boolean tiene_embosado = pertaben.tiene_embosado(tarjeta.getTarjetaDesplazado());
LogTarisan.logger.log(NivelLog.DEBUG, "HNA: tiene embosado?"+tiene_embosado+", tiene parametro troquelado?"+request.getParameter("TROQUELADO"));
if(!tiene_embosado && (request.getParameter("TROQUELADO") != null) && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
String pista2 = pac.getTarjeta().getPista2();
tarjeta.setPista2(pista2);
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(58);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_hna);
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
/*if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}else{*/
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
tades.setTroquelado(pac.getIdentificador());
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
// }
}
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado no esta casado y no puede acceder al analista");
sMensaje = "Este desplazado todavía no puede acceder a los servicios del anlaista";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
}
else if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de hna no tiene embosado y no esta casado.\n");
response.sendRedirect("../jsp/pac/gestor.jsp?embosado=1");
resul = true;
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de hna tiene embosado o ya esta casada.\n");
//Aceptamos las tarjetas de hna:
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
String pista2 = pac.getTarjeta().getPista2();
tarjeta.setPista2(pista2);
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(58);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_hna);
}/*else if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(pac.getTarjeta().getEntidadIMQ());
tades.setContrato(pac.getTarjeta().getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}*/
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
pac.setTarjeta(tarjeta); // Provisional
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_hna);
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(pac.getTarjeta().getEntidadIMQ());
tades.setContrato(pac.getTarjeta().getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
//Fin aceptamos las tarjetas de hna
}
}
else if(tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_dkv)==0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta de dkv");
//Verificamos si en ttbenefi tiene identificador:
PersistenciaTabenefi pertaben = new PersistenciaTabenefi();
boolean tiene_embosado = pertaben.tiene_embosado(tarjeta.getTarjetaDesplazado());
LogTarisan.logger.log(NivelLog.DEBUG, "DKV: tiene embosado?"+tiene_embosado+", tiene parametro troquelado?"+request.getParameter("TROQUELADO"));
if(!tiene_embosado && (request.getParameter("TROQUELADO") != null) && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd
if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), request.getParameter("TROQUELADO")))
{*/
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
Paciente pac = new Paciente();
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(32);
LogTarisan.logger.log(NivelLog.DEBUG, "Después de parsear la tarjeta el contrato es: "+tarjeta.getContrato());
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_dkv);
pac.set_noesiguala_inactivar(true);
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
/*if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}else{*/
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
tades.setTroquelado(pac.getIdentificador());
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
// }
}
if(!tiene_embosado)
{
/* insertar el identificador en bbdd */
}
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado no esta casado y no puede acceder al analista");
sMensaje = "Este desplazado todavía no puede acceder a los servicios del anlaista";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
//}
}
else if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0) )
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de dkv no tiene embosado\n");
response.sendRedirect("../jsp/pac/gestor.jsp?embosado=1");
resul = true;
}
else
{
Paciente pac = new Paciente();
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(32);
LogTarisan.logger.log(NivelLog.DEBUG, "Después de parsear la tarjeta el contrato es: "+tarjeta.getContrato());
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_dkv);
pac.set_noesiguala_inactivar(true);
}/*else if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}*/
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
/* if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)){
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");*/
/* insertar el identificador en bbdd */
/*if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}else{*/
/*PersistenciaTabenefi perBen = new PersistenciaTabenefi();
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}*/
// }
// }
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
}
/*
sMensaje = "La tarjeta no es de IMQ Navarra - Operativa no desarrollada<br/>Usar bacaladera";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
*/
}
else if(tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_sanitas)==0 || tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_sanitas.substring(1)) == 0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta de sanitas: ");
//Verificamos si en ttbenefi tiene identificador:
PersistenciaTabenefi pertaben = new PersistenciaTabenefi();
boolean tiene_embosado = pertaben.tiene_embosado(tarjeta.getTarjetaDesplazado());
//Por ahora las tarjetas de sanitas no van a necesitar el embosado aunque llamamos a la función está puesta una excepcion en el código para que si es
//sanitas siempre devuelva true
// 18/04/2016 SE INSERTA EN TADESPLAZ
if(!tiene_embosado && (request.getParameter("TROQUELADO") != null) && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd
if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), request.getParameter("TROQUELADO")))
{*/
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
Paciente pac = new Paciente();
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0)
{
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(5);
LogTarisan.logger.log(NivelLog.DEBUG, "Después de parsear la tarjeta el contrato es: "+tarjeta.getContrato());
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_sanitas);
pac.set_noesiguala_inactivar(true);
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
/*if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}else{*/
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
tades.setTroquelado(pac.getIdentificador());
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
// }
}
if(!tiene_embosado)
{
/* insertar el identificador en bbdd */
}
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
//}
}
else if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0) )
{
/*if(!tiene_embosado)
{*/
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de sanitas no tiene embosado\n");
response.sendRedirect("../jsp/pac/gestor.jsp?embosado=1");
resul = true;
}
else
{
Paciente pac = new Paciente();
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(tarjeta.getPoliza() == 0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "");
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(5);
}
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_sanitas);
}
else
{
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0){
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(pac.getTarjeta().getEntidadIMQ());
tades.setContrato(pac.getTarjeta().getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
/*if(!tiene_embosado)
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
// insertar el identificador en bbdd
if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}
}*/
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
}
/*
sMensaje = "La tarjeta no es de IMQ Navarra - Operativa no desarrollada<br/>Usar bacaladera";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
*/
}
else if(tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo)==0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta de IMQ Bilbao: "+tarjeta.getEntidadIMQ()+"-"+tarjeta.getColectivo()+"-"+tarjeta.getPoliza());
//Verificamos si en ttbenefi tiene identificador:
PersistenciaTabenefi pertaben = new PersistenciaTabenefi();
boolean tiene_embosado = pertaben.tiene_embosado(tarjeta.getTarjetaDesplazado());
LogTarisan.logger.log(NivelLog.DEBUG, "IMQ Bilbo: tiene embosado?"+tiene_embosado+", tiene parametro troquelado?"+request.getParameter("TROQUELADO"));
if(!tiene_embosado && (request.getParameter("TROQUELADO") != null) && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
//if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), request.getParameter("TROQUELADO")))
//{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
LogTarisan.logger.log(NivelLog.DEBUG, "Ya tenemos aqui el asegurado"+pac.getTarjeta().getEntidadIMQ()+" - "+pac.getTarjeta().getColectivo()+" - "+pac.getTarjeta().getPoliza()+" - "+pac.getTarjeta().getBeneficiario());
if(pac.getTarjeta().getPoliza() == 0)
{
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(3);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_imqbilbo);
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
sesion.setAttribute("PACIENTE", pac);
if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
tades.setTroquelado(pac.getIdentificador());
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado no esta casado y no puede acceder al analista");
sMensaje = "Este desplazado todavía no puede acceder a los servicios del anlaista";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
//}
}
else if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de imq bilbo no tiene embosado\n");
response.sendRedirect("../jsp/pac/gestor.jsp?embosado=1");
resul = true;
}
else
{
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
LogTarisan.logger.log(NivelLog.DEBUG, "Ya tenemos aqui el asegurado"+pac.getTarjeta().getEntidadIMQ()+" - "+pac.getTarjeta().getColectivo()+" - "+pac.getTarjeta().getPoliza()+" - "+pac.getTarjeta().getBeneficiario());
if(pac.getTarjeta().getPoliza() == 0)
{
tarjeta.setContrato(pac.getTarjeta().getContrato());
tarjeta.setEntidadIMQ(3);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_chipcard_imqbilbo);
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico).trim());
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
pac.setTarjeta(tarjeta);
pac.setDesplazado(tarjeta.getEntidadChipcard());
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
sesion.setAttribute("PACIENTE", pac);
if(pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0){
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(pac.getTarjeta().getEntidadIMQ());
tades.setContrato(pac.getTarjeta().getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
}
/*
sMensaje = "La tarjeta no es de IMQ Navarra - Operativa no desarrollada<br/>Usar bacaladera";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
*/
}
else if(tarjeta.getEntidadChipcard().compareTo(ParametrosConfiguracion.bin_redsa_asisa)==0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Tarjeta de ASISA");
//Verificamos si en ttbenefi tiene identificador:
PersistenciaTabenefi pertaben = new PersistenciaTabenefi();
boolean tiene_embosado = pertaben.tiene_embosado(tarjeta.getTarjetaDesplazado());
LogTarisan.logger.log(NivelLog.DEBUG, "ASISA: tiene embosado?"+tiene_embosado+", tiene parametro troquelado?"+request.getParameter("TROQUELADO"));
if(!tiene_embosado && (request.getParameter("TROQUELADO") != null) && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
/* insertar el identificador en bbdd */
//if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), request.getParameter("TROQUELADO")))
//{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0 )
{
//LogTarisan.logger.log(NivelLog.DEBUG, "\nDatos conseguidos: \n"+"Paciente.tarjeta.entidad="+tarjeta.getEntidadIMQ()+"\n"+"Paciente.tarjeta.contrato="+tarjeta.getContrato()+"\n");
//tarjeta.setContrato(pac.getTarjeta().getContrato());
//Los de asisa no nos dicen el contrato enlas pistas 1 ni 2 ponemos un 1 a fuego:
tarjeta.setContrato(1);
tarjeta.setEntidadIMQ(4);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_redsa_asisa);
LogTarisan.logger.log(NivelLog.DEBUG, "\nDatos conseguidos: \n"+"Paciente.tarjeta.entidad="+pac.getTarjeta().getEntidadIMQ()+"\n"+"Paciente.tarjeta.colectivo="+pac.getTarjeta().getEntidadIMQ()+"\n");
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico));
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
tades.setTroquelado(pac.getIdentificador());
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado no esta casado y no puede acceder al analista");
sMensaje = "Este desplazado todavía no puede acceder a los servicios del anlaista";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
//}
}
else if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "\nLa tarjeta de asisa no tiene embosado.\n");
response.sendRedirect("../jsp/pac/gestor.jsp?embosado=1");
resul = true;
}
else
{
Paciente pac = new Paciente();
//Si al llegar aquí ya hemos conseguido los datos, al parsear las pistas 1 y 2 el desplazado ha sido "casado" con su póliza de IMQ
// y no hay que volver a parsear la tarjeta.
if(tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0)
{
pac = parsearDesplazado_pistas1_2(valorTarjeta);
if(pac.getTarjeta().getPoliza() == 0 )
{
//LogTarisan.logger.log(NivelLog.DEBUG, "\nDatos conseguidos: \n"+"Paciente.tarjeta.entidad="+tarjeta.getEntidadIMQ()+"\n"+"Paciente.tarjeta.contrato="+tarjeta.getContrato()+"\n");
//tarjeta.setContrato(pac.getTarjeta().getContrato());
//Los de asisa no nos dicen el contrato enlas pistas 1 ni 2 ponemos un 1 a fuego:
tarjeta.setContrato(1);
tarjeta.setEntidadIMQ(4);
pac.setTarjeta(tarjeta);
pac.setDesplazado(ParametrosConfiguracion.bin_redsa_asisa);
LogTarisan.logger.log(NivelLog.DEBUG, "\nDatos conseguidos: \n"+"Paciente.tarjeta.entidad="+pac.getTarjeta().getEntidadIMQ()+"\n"+"Paciente.tarjeta.colectivo="+pac.getTarjeta().getEntidadIMQ()+"\n");
}
}
else
{
//Se ha parseado la tarjeta bien porque el desplazado esta casado pero no tenemos el nombre del asegurado
PersistenciaPaciente perpac = new PersistenciaPaciente();
pac.setNombre(perpac.obtenerNombreAsegurado(tarjeta,medico).trim());
LogTarisan.logger.log(NivelLog.DEBUG, "Se ha obtenido bien el nombre");
}
pac.setIdentificador(request.getParameter("TROQUELADO"));
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a introducir el troquelado si no lo tiene");
/*if(!tiene_embosado && (tarjeta.getBeneficiario()+tarjeta.getColectivo()+tarjeta.getPoliza() <= 0))
{
LogTarisan.logger.log(NivelLog.DEBUG, "No tiene metido el embosado hay que meterlo");*/
/* insertar el identificador en bbdd */
/*if(pertaben.añade_embosado(tarjeta.getTarjetaDesplazado(), pac.getIdentificador()))
{
LogTarisan.logger.log(NivelLog.INFO, "Se ha actualizado el identificador de la tarjeta chipcard: "+tarjeta.getTarjetaDesplazado());
}else{*/
/* PersistenciaTabenefi perBen = new PersistenciaTabenefi();
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}*/
// }
// }
pac.setTarjeta(tarjeta);
sesion.setAttribute("PACIENTE", pac);
if(!tiene_embosado && (pac.getTarjeta().getBeneficiario()+pac.getTarjeta().getColectivo()+pac.getTarjeta().getPoliza() <= 0)){
PersistenciaTabenefi perBen = new PersistenciaTabenefi();
PersistenciaTaDespla pertades = new PersistenciaTaDespla();
java.sql.Date fecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
Tadespla tades = new Tadespla();
tades.set_tarjeta(tarjeta.getTarjetaDesplazado());
tades.setNombre(pac.getNombre());
tades.setFecha_Alta(fecha);
tades.setEntidad_chipcard(tarjeta.getEntidadIMQ());
tades.setContrato(tarjeta.getContrato());
tades.setFecha_Registro(fecha);
//tades.setTroquelado(pac.getIdentificador());
tades.setTroquelado(perBen.obtenerIdentificador(tarjeta.getTarjetaDesplazado()));
if(pertades.Insertar_Tadespla(tades,intMedico)){
LogTarisan.logger.log(NivelLog.INFO, "Se ha insertado un nuevo movimiento en tadespla: "+tades.toString());
}else{
LogTarisan.logger.log(NivelLog.INFO, "NO SE HA PODIDO INSERTAR EN TADESPLA: "+tades.toString());
}
}
if (tarjeta.getEstadeBaja())
{
LogTarisan.logger.log(NivelLog.DEBUG, "El asegurado esta de baja!!!");
sMensaje = "La p&oacute;liza de la tarjeta est&aacute; de baja<br/>Contactar con IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ANALISTA)){
response.sendRedirect("../jsp/pac/analista.jsp?x=10&pagina=1");
}
else if (((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_RADIOLOGO)){
response.sendRedirect("../jsp/pac/radiologo.jsp?x=11&pagina=1");
}
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_REHABPOD) || ((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ATS))
response.sendRedirect("../jsp/pac/facturacion_rehabpod.jsp?x=1&pagina=1");
else if(((String)sesion.getAttribute("PERFIL")).equalsIgnoreCase(Constantes.PERFIL_ODONTOLOGIA)){
response.sendRedirect("../jsp/pac/facturacion_odon.jsp?x=2&pagina=1");
/*sMensaje = "Operativa no desarrollada";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );*/}
else
response.sendRedirect("../jsp/pac/facturacion_chipcard.jsp?x=0&pagina=1");
resul = true;
}
/*
sMensaje = "La tarjeta no es de IMQ Navarra - Operativa no desarrollada<br/> Usar bacaladera";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
*/
}
else
{
sMensaje = "Tarjeta de paciente erronea, puede estar caducada... <br/>El paciente debe ponerse en contacto con las oficinas de IMQ";
LogTarisan.logger.log(NivelLog.INFO, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
resul = false;
}
}
catch(Exception ex){
throw new ExcepcionTarisan(ex.toString());
}
return resul;
}
/**
*
* @param valorTarjeta
* @return
* @throws ExcepcionTarisan
*/
//private Tarjeta parsearTarjeta_pista2(String valorTarjeta) throws ExcepcionTarisan
private static Tarjeta parsearTarjeta_pista2(String valorTarjeta) throws ExcepcionTarisan
{
//=803431000000000001947068=001000010811%
//=803431460000000002031478=006000017606%
//=803431300000000002098236=300000011001%
//=803431460000000002114365=006000011208%
Tarjeta tarjeta = new Tarjeta();
tarjeta.setValida(false);
PersistenciaTaiguala pertaiguala = new PersistenciaTaiguala();
try
{
boolean cumple_Luhn = Utilidades.calcularLuhn(valorTarjeta.substring(1,25));
LogTarisan.logger.log(NivelLog.DEBUG, "Cumple el luhn: "+cumple_Luhn);
boolean esnuestra = Utilidades.tarjetaNuestraoDesplazado(valorTarjeta.substring(1,7));
LogTarisan.logger.log(NivelLog.DEBUG, "Es nuestra:"+esnuestra);
if(cumple_Luhn && esnuestra)
{
tarjeta.setTarjeta(Integer.parseInt(valorTarjeta.substring(16,24)));
tarjeta.setTarjetaDesplazado(valorTarjeta.substring(1,25));
LogTarisan.logger.log(NivelLog.DEBUG,"Número tarjeta: "+valorTarjeta.substring(16,24));
if(valorTarjeta.contains("==="))
{
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a ver si leemos las tarjetas de sanitas viejas...");
tarjeta.setTarjeta(Integer.parseInt(valorTarjeta.substring(16,22)));
tarjeta.setContrato(Integer.parseInt(valorTarjeta.substring(26, 29)));
}
StringBuffer sqlSelect = new StringBuffer();
sqlSelect.append("SELECT COLECTIVO");
sqlSelect.append(", POLIZA");
sqlSelect.append(", FECHA_BAJA");
sqlSelect.append(", ORDEN");
sqlSelect.append(", ENTIDAD");
sqlSelect.append(" FROM ttbenefi");
sqlSelect.append(" WHERE TARJETA = ? and fecha_alta <= sysdate");
//sqlSelect.append(" AND POLIZA = ?");
//sqlSelect.append(" AND ORDEN = ?");
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
Object aCondiciones[] = new Object[1];
aCondiciones[0] = Integer.valueOf(tarjeta.getTarjeta());
//aCondiciones[1] = Double.valueOf(tarjeta.getPoliza());
//aCondiciones[2] = Integer.valueOf(tarjeta.getBeneficiario());
int numTarjeta = 0;
int codCliente = 0;
Date fecBaja = null;
String autorizado = "";
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect.toString(), aCondiciones);
if(rs.next())
{
tarjeta.setColectivo(rs.getLong("COLECTIVO"));
tarjeta.setPoliza(rs.getLong("POLIZA"));
fecBaja = rs.getDate("FECHA_BAJA");
tarjeta.setBeneficiario(rs.getInt("ORDEN"));
tarjeta.setEntidadIMQ(rs.getInt("ENTIDAD"));
tarjeta.setValida(true);
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);
int contrato = pertaiguala.obtenerContrato(tarjeta.getColectivo(), tarjeta.getPoliza(), tarjeta.getEntidadIMQ());
if(contrato > 0)
tarjeta.setContrato(contrato);
else
LogTarisan.logger.log(NivelLog.ERROR, "Error al obtener el contrato, tarjeta: "+tarjeta.getTarjeta());
}
else if(!cumple_Luhn)
{
LogTarisan.logger.log(NivelLog.ERROR, "Se ha pasado una tarjeta que no cumple el LUHN");
//%8034310001779851
// 803431
if(esnuestra)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Podemos tener una tarjeta de sanitas. "+valorTarjeta.substring(8,16));
tarjeta.setEntidadChipcard(ParametrosConfiguracion.bin_chipcard_propios);
tarjeta.setTarjeta(Integer.parseInt(valorTarjeta.substring(8,16)));
StringBuffer sqlSelect = new StringBuffer();
sqlSelect.append("SELECT COLECTIVO");
sqlSelect.append(", POLIZA");
sqlSelect.append(", FECHA_BAJA");
sqlSelect.append(", ORDEN");
sqlSelect.append(", ENTIDAD");
sqlSelect.append(" FROM ttbenefi");
sqlSelect.append(" WHERE TARJETA = ? and fecha_alta <= sysdate");
//sqlSelect.append(" AND POLIZA = ?");
//sqlSelect.append(" AND ORDEN = ?");
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
Date fecBaja = null;
Object aCondiciones[] = new Object[1];
aCondiciones[0] = Integer.valueOf(tarjeta.getTarjeta());
//aCondiciones[1] = Double.valueOf(tarjeta.getPoliza());
//aCondiciones[2] = Integer.valueOf(tarjeta.getBeneficiario());
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect.toString(), aCondiciones);
while(rs.next())
{
tarjeta.setColectivo(rs.getInt("COLECTIVO"));
tarjeta.setPoliza(rs.getLong("POLIZA"));
fecBaja = rs.getDate("FECHA_BAJA");
tarjeta.setBeneficiario(rs.getInt("ORDEN"));
tarjeta.setEntidadIMQ(rs.getInt("ENTIDAD"));
tarjeta.setValida(true);
}
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
int contrato = pertaiguala.obtenerContrato(tarjeta.getColectivo(), tarjeta.getPoliza(), tarjeta.getEntidadIMQ());
if(contrato > 0)
tarjeta.setContrato(contrato);
else
LogTarisan.logger.log(NivelLog.ERROR, "Error al obtener el contrato, tarjeta: "+tarjeta.getTarjeta());
}
else
{
//ni cumple el luhn ni es nuestra
//Aunque no cumple el luhn hay que parsearla por ser tarjeta de antares
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 2773:"+valorTarjeta.substring(1,25));
PersistenciaTabenefi per = new PersistenciaTabenefi();
tarjeta = per.generarObjetoTarjetaChipcard(valorTarjeta.substring(1,25), 0);
tarjeta.setValida(true);
if(valorTarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
tarjeta.setEntidadChipcard("803446");
if(valorTarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_hna) == 0)
tarjeta.setEntidadChipcard("803497");
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n\nTenemos tarjeta de desplazado!!");
}
}
else //cumple el luhn pero no es nuestra
{
/*
* vamos a buscar en ttbenefi si existe la tarjeta_chipcard para obtener col, pol, orden
*/
//LogTarisan.logger.log(NivelLog.DEBUG, "chipcardContrato :"+valorTarjeta.substring(valorTarjeta.indexOf("=")+1, valorTarjeta.indexOf("=")+4));
//Hay tarjetas que se leen con los separadores cambiados: %B80344400003916104804440&ANGEL CANTERA ORTIZ &001160127608%803444000039161048044405001601210000
String contrato = "";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3899");
if(valorTarjeta.indexOf("=")>0)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3901");
contrato = valorTarjeta.substring(valorTarjeta.indexOf("=")+1, valorTarjeta.indexOf("=")+4);
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3906"+valorTarjeta.indexOf(""));
contrato = valorTarjeta.substring(valorTarjeta.indexOf("")+1, valorTarjeta.indexOf("")+4);
}
tarjeta.setContrato(Integer.parseInt(contrato));
if(valorTarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_imqbilbo) == 0)
{
//La tarjeta es del imq de bilbo, la marcamos como tal para que muestre el mensaje.
PersistenciaTabenefi per = new PersistenciaTabenefi();
tarjeta = per.generarObjetoTarjetaChipcard(valorTarjeta.substring(1,25), 0);
tarjeta.setValida(true);
tarjeta.setEntidadIMQ(3);
tarjeta.setEntidadChipcard("803444");
LogTarisan.logger.log(NivelLog.DEBUG, "Es de IMQ bilbo, le ponemos la entidad 3");
}
else
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 2773:"+valorTarjeta.substring(1,25));
PersistenciaTabenefi per = new PersistenciaTabenefi();
tarjeta = per.generarObjetoTarjetaChipcard(valorTarjeta.substring(1,25), 0);
tarjeta.setValida(true);
if(valorTarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_adeslas) == 0)
tarjeta.setEntidadChipcard("803446");
if(valorTarjeta.substring(1,7).compareTo(ParametrosConfiguracion.bin_chipcard_hna) == 0)
tarjeta.setEntidadChipcard("803497");
LogTarisan.logger.log(NivelLog.DEBUG, "\n\n\nTenemos tarjeta de desplazado!!");
}
}
}
catch(Exception ex)
{
throw new ExcepcionTarisan(ex.toString());
}
LogTarisan.logger.log(NivelLog.DEBUG, "Fin parsear tarjeta pista 2");
return tarjeta;
}
/**
* Parsea la tarjeta del paciente para recoger los campos necesarios de la misma.
* @param valorTarjeta El <code>String</code> leído en la pista 3 de la tarjeta del paciente.
* @return El objeto <code>Tarjeta</code> correspondiente al paciente.
*/
private Tarjeta parsearTarjeta_pista3(String valorTarjeta) throws ExcepcionTarisan
{
Tarjeta tarjeta = new Tarjeta();
tarjeta.setValida(false);
PersistenciaTaiguala pertaiguala = new PersistenciaTaiguala();
try
{
tarjeta.setTarjeta(Integer.parseInt(valorTarjeta.substring(0, 8)));
//tarjeta.setContrato(Integer.parseInt(valorTarjeta.substring(12, 15)));
//boolean cumple_Luhn = Utilidades.calcularLuhn(valorTarjeta.substring(0,24));
/* Con las tarjetas de los colectivos muy largos nos da problemas... vamos a buscarlos en la bbdd
tarjeta.setColectivo(Integer.parseInt(valorTarjeta.substring(15, 20)));
tarjeta.setPoliza(Double.parseDouble(valorTarjeta.substring(20, 32)));
tarjeta.setBeneficiario(Integer.parseInt(valorTarjeta.substring(32, 34)));
*/
StringBuffer sqlSelect = new StringBuffer();
sqlSelect.append("SELECT COLECTIVO");
sqlSelect.append(", POLIZA");
sqlSelect.append(", FECHA_BAJA");
sqlSelect.append(", ORDEN");
sqlSelect.append(", ENTIDAD");
sqlSelect.append(" FROM ttbenefi");
sqlSelect.append(" WHERE TARJETA = ? and fecha_alta <= sysdate");
//sqlSelect.append(" AND POLIZA = ?");
//sqlSelect.append(" AND ORDEN = ?");
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
Object aCondiciones[] = new Object[1];
aCondiciones[0] = Integer.valueOf(tarjeta.getTarjeta());
//aCondiciones[1] = Double.valueOf(tarjeta.getPoliza());
//aCondiciones[2] = Integer.valueOf(tarjeta.getBeneficiario());
int numTarjeta = 0;
int codCliente = 0;
Date fecBaja = null;
String autorizado = "";
ResultSet rs = ParametrosConfiguracion.dataStore.seleccionar(conexion, sqlSelect.toString(), aCondiciones);
while(rs.next())
{
tarjeta.setColectivo(rs.getLong("COLECTIVO"));
tarjeta.setPoliza(rs.getLong("POLIZA"));
fecBaja = rs.getDate("FECHA_BAJA");
tarjeta.setBeneficiario(rs.getInt("ORDEN"));
tarjeta.setEntidadIMQ(rs.getInt("ENTIDAD"));
tarjeta.setValida(true);
}
tarjeta.setContrato(pertaiguala.obtenerContrato(tarjeta.getColectivo(),tarjeta.getPoliza(), tarjeta.getEntidadIMQ()));
rs.close();
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
}
catch(NumberFormatException ex)
{
throw new ExcepcionTarisan(ex.toString());
}
catch(StringIndexOutOfBoundsException ex)
{
throw new ExcepcionTarisan(ex.toString());
}
catch(Exception ex)
{
throw new ExcepcionTarisan(ex.toString());
}
return tarjeta;
}
/**
* Obtiene el mensaje de error correspondiente al paso de una tarjeta de paciente errónea.
* @param nMensaje Número del mensaje.
* @return El mensaje correspondiente.
*/
public static String obtenerMensaje(Integer nMensaje)
{
String mensaje = "";
if(nMensaje.equals(TARJETA_CADUCADA))
{
mensaje = "Tarjeta caducada, se ha emitido otra posterior";
}
else if(nMensaje.equals(TARJETA_BAJA))
{
mensaje = "Beneficiario de baja";
}
else if(nMensaje.equals(TARJETA_SUSPENSO))
{
mensaje = "Póliza en suspenso, pasar por oficina IMQ";
}
else if(nMensaje.equals(TARJETA_AUTORIZACION))
{
mensaje = "Acceso denegado a la aplicación, el beneficiario no ha firmado la autorización correspondiente";
}
else if(nMensaje.equals(TARJETA_FIRMA_AUTORIZACION))
{
mensaje = "Solicitud de la autorización del beneficiario";
}
else
{
mensaje = "OK";
}
return mensaje;
}
/**
* Comprueba la compatibilidad de un paciente con una especialidad, según sexo o edad
* @param paciente
* @param especialidad
* @return 1 si es compatible, 2 si el sexo no es compatible con la especialidad, 3 si ha ido al pediatra y tiene 15 o más...
*/
private int especialidadCompatible(Paciente paciente, int especialidad)
{
int compatible = 1;
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 2042: Sexo" + paciente.getSexo() + ", sexo.compareToIgnoreCase('H'): "+paciente.getSexo().compareToIgnoreCase("H"));
if (especialidad == 31 && paciente.getSexo().compareToIgnoreCase("H") == 0)
{
compatible=2;
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 2047: Edad" + paciente.getEdad()+ ", Especialidad:" + especialidad);
if (especialidad == 2 && paciente.getEdad() > 14)
{
compatible=3;
}
return compatible;
}
private boolean insertarVolanteIngreso(HttpServletRequest request, HttpServletResponse response, HttpSession sesion)
{
boolean resultado=false;
try
{
LogTarisan.logger.log(NivelLog.DEBUG, "Entramos en insertarVolanteIngreso");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3070");
Tavolin tavolin = new Tavolin();
String fecha = request.getParameter("fec_paciente");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3073 : "+request.getParameter("nom_paciente"));
String[] arrFecha = fecha.split("/");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3075 : "+arrFecha[2] + "-" + arrFecha[1] + "-" + arrFecha[0]);
String mes = arrFecha[1];
String dia = arrFecha[0];
mes = mes.length() < 2 ? "0"+mes : mes;
dia = dia.length() < 2 ? "0"+dia : dia;
java.sql.Date dtFecha = new java.sql.Date(java.sql.Date.valueOf(arrFecha[2] + "-" + mes + "-" + dia).getTime());
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3076");
java.sql.Date hoy = new java.sql.Date(Calendar.getInstance().getTime().getTime());
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3079");
tavolin.set_fecha(hoy);
tavolin.set_nombre(request.getParameter("nom_paciente"));
tavolin.set_domicilio(request.getParameter("dir_paciente"));
tavolin.set_fecnac(dtFecha);
tavolin.set_nif(request.getParameter("nif_paciente"));
tavolin.set_medico(((Usuario)sesion.getAttribute("USUARIO")).getMedico());
tavolin.set_poliza(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo() +" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario());
tavolin.set_acto(Integer.parseInt(request.getParameter("acto_medico")));
tavolin.set_motivo(Integer.parseInt(request.getParameter("motivo_ingreso")));
tavolin.set_juicio(request.getParameter("diagnostico"));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3090");
if(((Paciente)sesion.getAttribute("PACIENTE")).getDesplazado().compareTo(ParametrosConfiguracion.bin_chipcard_propios) == 0)
tavolin.set_tarjeta(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjeta());
else
tavolin.set_tarjeta(Long.parseLong(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado()));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3095");
PersistenciaTavolin pertavolin = new PersistenciaTavolin();
if(pertavolin.insertar(tavolin))
{
LogTarisan.logger.log(NivelLog.INFO, "Insercion correcta del volante de ingreso");
resultado = true;
}
}
catch (Exception ex)
{
try {
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion al insertar el volante de ingreso: "+ex.toString());
String sMensaje = "Excepcion al insertar el volante de ingreso";
LogTarisan.logger.log(NivelLog.ERROR, sMensaje);
sesion.setAttribute("ERROR", sMensaje);
response.sendRedirect("../jsp/error.jsp" );
} catch (IOException e) {
LogTarisan.logger.log(NivelLog.ERROR, "Excepcion al insertar el volante de ingreso: "+e.toString());
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Fin insertarVolanteIngreso, con resultado : "+resultado);
return resultado;
}
private boolean insertarPrescripcionAutorizacion(HttpServletRequest request, HttpServletResponse response, HttpSession sesion)
{
boolean resultado = true;
try {
/*
* <input type="hidden" name="listaElementosPrescripcion" value="">
<input type="hidden" name="listaCodigoElementosPrescripcion" value="">
<input type="hidden" name="unidadesElementosPrescripcion" value="">
<input type="hidden" name="informePrescripcion" value="">
<input type="hidden" name="OPCION" value="<%=Constantes.OPC_PAC_PRESCRIPCION_ATS%>">
<input type="hidden" name="justificacionPrescripcion" value='<%=strJustificacionPrescripcion%>'>
*/
String listaCodigos = (String)request.getParameter("listaCodigoElementosPrescripcion");
String listaUnidades = (String)request.getParameter("unidadesElementosPrescripcion");
String informe = (String)request.getParameter("informePrescripcion");
PersistenciaTaconaut perta = new PersistenciaTaconaut();
ArrayList arrayCodigos= new ArrayList();
ArrayList arrayUnidades = new ArrayList();
StringTokenizer st = new StringTokenizer(listaCodigos, "¬");
while (st.hasMoreTokens())
{
String token = st.nextToken();
if(token.length()>0)
{
arrayCodigos.add(Integer.parseInt(token));
}
}
st = new StringTokenizer(listaUnidades, "¬");
while(st.hasMoreTokens())
{
String token = st.nextToken();
if(token.length()>0)
{
arrayUnidades.add(Integer.parseInt(token));
}
}
PersistenciaTareglog pertareg = new PersistenciaTareglog();
PersistenciaTamedico pertamedico = new PersistenciaTamedico();
int medico = ((Usuario)sesion.getAttribute("USUARIO")).getMedico();
int especialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad();
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 3347: "+(String)request.getParameter("especialidad"));
if(request.getParameter("especialidad") != null)
especialidad = Integer.parseInt((String)request.getParameter("especialidad"));
Timestamp tsFechaUltimoAcceso = ((Usuario)sesion.getAttribute("USUARIO")).getFechaUltAcceso();
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
//obtenemos el valor del campo param1 del medico conectado
//este valor se utiliza para calcular el numero de autorizacion para la prescripcion a realizar
int intParam1=pertamedico.obtenerValorParam1(medico);
//obtenemos el ultimo valor del campo correlativo de la tabla tareglog.
//Este campo es un numero correlativo utilizado para diferenciar las claves.
int intUltimoValorCorrelativo = pertareg.obtenerUltimoValorCorrelativo(medico, tsFechaUltimoAcceso);
//calculamos el numero de autorizacion para la prescripcion a realizar
long autorizacion = this.calcularCodigoAutorizacion(medico, intParam1);
//obtenemos la tarjeta del paciente de sesion
String tarjeta = "";
if(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjeta() == 0)
tarjeta = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjetaDesplazado();
else
tarjeta = String.valueOf(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getTarjeta());
if(autorizacion < 1)
autorizacion = 1;
for(int i=0; i<arrayCodigos.size(); i++)
{
LogTarisan.logger.log(NivelLog.DEBUG, "GestorPacientes creamos autorizacion: "+autorizacion+" "+medico+" "+especialidad+" "+(Integer)arrayCodigos.get(i)+" "+(Integer)arrayUnidades.get(i)+" 0 "+tarjeta);
if(autorizacion == 0 || medico == 0 || especialidad == 0 || (Integer)arrayCodigos.get(i) == 0 || (Integer)arrayUnidades.get(i) == 0 || informe.length() == 0 || tarjeta.length() == 0 )
resultado = false;
if(resultado)
{
if(perta.CrearAutorizacionValida(autorizacion, medico, especialidad, (Integer)arrayCodigos.get(i), (Integer)arrayUnidades.get(i), informe, 0, tarjeta) && resultado)
resultado = true;
else
resultado = false;
}
}
if(resultado)
{
Calendar fecha = Calendar.getInstance();
Timestamp fechaAcceso = new Timestamp(fecha.getTimeInMillis());
pertareg.insertarLog(medico, fechaAcceso, fecha, intUltimoValorCorrelativo, "taconaut", "insert into taconaut (autorizacion, especialidad, acto, cantidad, medico, informe, from_gesigu, tarjeta) values ", "autorizacion para ats insertada con exito");
//actualizamos el valor del campo param1
StringBuffer strSql = new StringBuffer();
strSql.append("UPDATE TAMEDICO");
strSql.append(" SET PARAM1=?");
strSql.append(" WHERE MEDICO=?");
Object[] aValores = new Object[1];
aValores[0] = Integer.valueOf(intParam1 + 1);
Object[] aCondiciones = new Object[1];
aCondiciones[0] = Integer.valueOf(medico);
Connection conexion = ParametrosConfiguracion.dataStore.obtenerConexion();
pertamedico.modificarMedico(strSql.toString(), aValores, aCondiciones, conexion);
ParametrosConfiguracion.dataStore.liberarConexion(conexion);
request.setAttribute("autorizacion", autorizacion);
}
} catch (ExcepcionTarisan e) {
LogTarisan.logger.log(NivelLog.ERROR, "Error al insertar en tareglog la autorizacion de ATS");
resultado = false;
}
return resultado;
}
private void generarPDFRecetas(HttpServletRequest request, HttpServletResponse response, HttpSession sesion, int tipoDoc) throws ExcepcionTarisan
{
try
{
String strMedico = ((Usuario)sesion.getAttribute("USUARIO")).getNombreCab().toString();
String strDireccion = ((Usuario)sesion.getAttribute("USUARIO")).getDireccionCab().toString();
String strEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidadCab().toString();
String strPoblacion = ((Usuario)sesion.getAttribute("USUARIO")).getPoblacionCab();
String strNumColegiado = "Num. Colegiado: " + ((Usuario)sesion.getAttribute("USUARIO")).getColegiadoCab().toString();
String strTelefono = ((Usuario)sesion.getAttribute("USUARIO")).getTelefonoCab().toString();
String strIngreso = (String)request.getParameter("num_ingreso");
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String strMensajeSinElementos="No ha seleccionado ningún acto médico.";
//ArrayList que contedrá las descripciones de analíticas
ArrayList arrayListaElementosPrescripcion = null;
//Arraylist que tiene el número de actos...
ArrayList arrayListaUnidades = new ArrayList();
// Informacion al farmaceutico
String strInforme = "";
if (request.getParameter("informePrescripcion") != null) {
strInforme =(String)request.getParameter("informePrescripcion");
}
// Informacion al farmaceutico
String strInstrucciones = "";
if (request.getParameter("instruccionesPaciente") != null) {
strInstrucciones =(String)request.getParameter("instruccionesPaciente");
}
// Posologia
String strInformePosologia = "";
if (request.getParameter("informePrescripcionPosologia") != null) {
strInformePosologia =(String)request.getParameter("informePrescripcionPosologia");
}
// Duración del tratamiento
String strDias = "";
if (request.getParameter("dias") != null) {
strDias =(String)request.getParameter("dias");
}
//Lista de elementos de Prescripción
String strListaElementosPrescripcion = "";
String strListaElementosPrescripcionAux = "";
String strListaUnidades = "";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 233");
if (request.getParameter("listaElementosPrescripcion") != null ) {
LogTarisan.logger.log(NivelLog.DEBUG, "Se van a insertar los siguientes codigos de analitica: "+(String)request.getParameter("listaCodigoElementosPrescripcion"));
strListaElementosPrescripcion = (String)request.getParameter("listaElementosPrescripcion");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
}
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
strListaElementosPrescripcionAux = strListaElementosPrescripcion.replace('\'', '~');
}
strListaElementosPrescripcion = strListaElementosPrescripcionAux;
while(strListaElementosPrescripcion.indexOf("~") != -1) {
strListaElementosPrescripcion = strListaElementosPrescripcion.replace('~','\'');
}
//Vector vElementosPrescripcion = new Vector();
arrayListaElementosPrescripcion = new ArrayList();
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 246");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
// Lista no vacía
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
//Separamos las diferentes determinaciones
int i = 0;
while (strListaElementosPrescripcion.indexOf("¬") != -1) {
//vElementosPrescripcion.add(strListaElementosPrescripcion.substring(0, strListaElementosPrescripcion.indexOf("¬")));
arrayListaElementosPrescripcion.add(strListaElementosPrescripcion.substring(0, strListaElementosPrescripcion.indexOf("¬")));
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
i++;
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 259");
ArrayList temp = new ArrayList();
strListaUnidades = (String)request.getParameter("unidadesElementosPrescripcion");
if(strListaUnidades != null)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 261"+strListaUnidades);
strListaUnidades = strListaUnidades.substring(1);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 264");
while(strListaUnidades.indexOf("¬") != -1)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 267");
arrayListaUnidades.add(strListaUnidades.substring(0, strListaUnidades.indexOf("¬")));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 269: - "+strListaUnidades.substring(0, strListaUnidades.indexOf("¬")));
strListaUnidades = strListaUnidades.substring(strListaUnidades.indexOf("¬") + 1);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 271");
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 274");
for(int i = 0; i<arrayListaElementosPrescripcion.size(); i++)
{
temp.add(arrayListaElementosPrescripcion.get(i) + " - Uds: " + arrayListaUnidades.get(i));
}
arrayListaElementosPrescripcion = temp;
}
}
String strListaCodigoElementos = "";
if (request.getParameter("listaCodigoElementosPrescripcion")!=null) {
strListaCodigoElementos=(String)request.getParameter("listaCodigoElementosPrescripcion");
}
String strNomPaciente = "";
PersistenciaPaciente per = new PersistenciaPaciente();
String strfecnac = "00/00/0000";
Calendar fecnac = Calendar.getInstance();
String strnif = "";
if(sesion.getAttribute("PACIENTE") == null)
{
LogTarisan.logger.log(NivelLog.DEBUG, "No hay paciente en sesión, lo cojemos de los parámetros.");
strNomPaciente = (String)request.getParameter("nom_paciente");
Tarjeta tar = new Tarjeta();
tar.setTarjeta(Integer.valueOf((String)request.getParameter("tarjeta")));
fecnac = per.obtenerFechaNacimiento(tar,((Usuario)sesion.getAttribute("USUARIO")).getMedico());
if(fecnac != null)
strfecnac = fecnac.get(Calendar.DAY_OF_MONTH)+"/"+(fecnac.get(Calendar.MONTH)+1)+"/"+fecnac.get(Calendar.YEAR);
strnif = per.obtenerNIF(tar,((Usuario)sesion.getAttribute("USUARIO")).getMedico());
}
else
{
strNomPaciente = ((Paciente)sesion.getAttribute("PACIENTE")).getNombre();
fecnac = per.obtenerFechaNacimiento(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
if(fecnac != null)
strfecnac = fecnac.get(Calendar.DAY_OF_MONTH)+"/"+(fecnac.get(Calendar.MONTH)+1)+"/"+fecnac.get(Calendar.YEAR);
strnif = per.obtenerNIF(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
}
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 = "";
//strFile = ParametrosConfiguracion.ruta_pdf+"Receta_" + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_recetas + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
document.open();
PdfPTable table = new PdfPTable(2); //Numero de columnas
//Fijar anchura de la tabla
table.setWidthPercentage(100);
//AÑADIR TABLA
table.setHorizontalAlignment(Element.ALIGN_CENTER);
document.add(table);
Print print = new Print();
// DIBUJAMOS EL TEXTO //
PdfContentByte cb = writer.getDirectContent();
cb.stroke();
BaseFont bf = BaseFont.createFont();
cb.beginText();
cb.setFontAndSize(bf, 8);
//AÑADIR LOGOTIPO
int intMedico=((Usuario)sesion.getAttribute("USUARIO")).getMedico();
PersistenciaTamedico perT = new PersistenciaTamedico();
/*if(perT.obtenerPosicionLogotipo(intMedico)!=null){
if(perT.obtenerPosicionLogotipo(intMedico).equals("I")){
document = print.anadirLogotipo(document, intMedico, 50, 780);
document = print.anadirLogotipo(document, intMedico, 50, 375);
}else if(perT.obtenerPosicionLogotipo(intMedico).equals("D")){
document = print.anadirLogotipo(document, intMedico, 500, 780);
document = print.anadirLogotipo(document, intMedico, 500, 375);
}
}*/
if(perT.obtenerPosicionLogotipo(intMedico)!=null){
if(perT.obtenerPosicionLogotipo(intMedico).equals("I")){
document = print.anadirLogotipo(document, intMedico, 50, 780);
document = print.anadirLogotipo(document, intMedico, 50, 375);
}else{
document = print.anadirLogotipo(document, intMedico, 500, 780);
document = print.anadirLogotipo(document, intMedico, 500, 375);
}
}
// Duración tratamiento
String txtDias = strDias;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtDias, 250, 740, 0); // (align, texto, X, Y, Rotacion)
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtDias, 250, 335, 0);
// Posología
String txtPosologia = strInformePosologia;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtPosologia, 250, 718, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtPosologia, 250, 312, 0);
// Paciente
String txtNombrePac = strNomPaciente;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtNombrePac, 365, 720, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtNombrePac, 365, 330, 0);
String txtDNI = "Dni: " + strnif;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtDNI, 365, 705, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtDNI, 365, 315, 0);
String txtFecNac = "Fecha nacimiento: " + strfecnac;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtFecNac, 365, 690, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtFecNac, 365, 300, 0);
// Medico
String txtNombreMed = strMedico;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtNombreMed, 365, 640, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtNombreMed, 365, 239, 0);
String txtNumColeg = strNumColegiado;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtNumColeg, 365, 625, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtNumColeg, 365, 224, 0);
String txtEspe = strEspecialidad;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtEspe, 365, 610, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtEspe, 365, 209, 0);
String txtDirecPobl = strDireccion + ", " + strPoblacion;
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtDirecPobl, 365, 595, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtDirecPobl, 365, 194, 0);
dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String fechaHoy = sdfFormateadorFecha.format(dtFecha);
String dia="";
String mes="";
String anio="";
dia = fechaHoy.substring(0, 2);
mes = fechaHoy.substring(3, 5);
anio = fechaHoy.substring(6, 10);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, dia + " " + mes + " " + anio , 368, 568, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, dia + " " + mes + " " + anio , 363, 171, 0);
// Actos médicos
String acto="";
int espacio=0;
for (int i=0;i<arrayListaElementosPrescripcion.size();i++) {
if (arrayListaElementosPrescripcion.get(i) != null) {
acto = (String)arrayListaElementosPrescripcion.get(i);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, acto, 50, 675-espacio, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, acto, 50, 270-espacio, 0);
espacio+=15;
}
// Posología debajo de los actos médicos
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "POSOLOGIA:", 50, 615, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtPosologia, 50, 605, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, "POSOLOGIA:", 50, 200, 0);
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, txtPosologia, 50, 190, 0);
// Informacion al farmacéutico
String informeFarma = strInforme;
String strLinea="";
int intLinea = (informeFarma.length()/45) + 1;
if (informeFarma.length() <= 45){
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, informeFarma, 50, 540, 0);
}else{
int x = 0;
for (int i=0; i < intLinea; i ++){
if(informeFarma.length() <= 45){
strLinea = informeFarma;
}else{
strLinea = informeFarma.substring(0, 45);
informeFarma = informeFarma.substring(45);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, 540 - x, 0);
x += 10;
}
}
// Instrucciones al paciente
String instruccionesPac = strInstrucciones;
strLinea="";
intLinea = (instruccionesPac.length()/135) + 1;
if (instruccionesPac.length() <= 135){ // Controlar salto de linea
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, instruccionesPac, 50, 105, 0);
}else{
int x = 0;
for (int i=0; i < intLinea; i ++){
if(instruccionesPac.length() <= 135){
strLinea = instruccionesPac;
}else{
strLinea = instruccionesPac.substring(0, 135);
instruccionesPac = instruccionesPac.substring(135);
}
cb.showTextAligned(PdfContentByte.ALIGN_LEFT, strLinea, 50, 105 - x, 0);
x += 10;
}
}
cb.endText();
//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 generarPDFDetalle (HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
String strTexto = "";
try
{
//Creamos el documento
Document document = new Document();
//Fijamos Márgenes
document.setMargins(40, 40, 5, 5);
/*String strFile = "/root/apache-tomcat-6.0.20/webapps/tarisan/peticiones/DetallePaciente_" + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";*/
String strFile = ParametrosConfiguracion.ruta_pdf_peticiones_detalle_pacientes + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a generar el PDF del detalle de pacientes");
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
// step 3: we open the document
document.open();
Print print = new Print();
//Definicion Fuentes
Font fuente1= new Font();
fuente1.setSize(18);
fuente1.setStyle(Font.BOLD);
Font fuente2= new Font();
fuente2.setSize(9);
Font fuente3= new Font();
fuente3.setSize(5);
Font fuente4= new Font();
fuente4.setSize(10);
fuente4.setStyle(Font.BOLD);
Font fuente5= new Font();
fuente5.setSize(9);
fuente5.setStyle(Font.BOLD);
Font fuente6= new Font();
fuente6.setSize(8);
fuente6.setStyle(Font.BOLD);
//Definicion Celda en blanco
PdfPCell celdaLibre = new PdfPCell(new Paragraph(" ",fuente1));
celdaLibre.setColspan(3); // Indicamos cuantas columnas ocupa la celda
celdaLibre.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaLibre2 = new PdfPCell(new Paragraph(" ",fuente3));
celdaLibre2.setColspan(3); // Indicamos cuantas columnas ocupa la celda
celdaLibre2.setBorder(PdfPCell.NO_BORDER);
//Definición de la tabla exterior
PdfPTable tableExterior = new PdfPTable(3); //Numero de comlumnas de la tabla
tableExterior.setWidthPercentage(100);
float[] headerWidths={260,350,60}; //Tamaño(Anchura) de las columnas
tableExterior.setWidths(headerWidths);
//Para que por defecto todas sus celdas salgan sin borde: tableExterior.getDefaultCell().setBorder(Rectangle.NO_BORDER);
int pos = 0; // Variable en la que guardamos la posicion que utilizamos para ajustar textos a la derecha
//AÑADIR LOGOTIPO
int intMedico=((Usuario)sesion.getAttribute("USUARIO")).getMedico();
document = print.anadirLogotipo(document, intMedico,45,780);
//AÑADIR CABECERA
strTexto = "Impresión Detalle Pacientes";
String strFecha = "";
String dia="";
String mes="";
String anio="";
if (request.getParameter("fecha") != null) {
strFecha = request.getParameter("fecha");
dia = strFecha.substring(0, 2);
mes = strFecha.substring(3, 5);
anio = strFecha.substring(6, 10);
//strFecha = dia+"/"+mes+"/"+anio;
//strFecha = strFecha.replaceAll("-", "/");
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
// Si desea crear una celda de mas de una columna. Cree un objecto Cell y cambie su propiedad span
PdfPCell celdaTitulo = new PdfPCell(new Paragraph(" " + strTexto,fuente1));
celdaTitulo.setColspan(3); // Indicamos cuantas columnas ocupa la celda
celdaTitulo.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTitulo);
//Celda en blanco
tableExterior.addCell(celdaLibre);
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("RELAción ACTOS MédicoS REALIZADOS",fuente5));
celdaSubTitulo.setColspan(3); // Indicamos cuantas columnas ocupa la celda
//celdaSubTitulo.setBorder(PdfPCell.NO_BORDER);
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
//Celda en blanco
tableExterior.addCell(celdaLibre2);
PdfPCell celdaFecha = new PdfPCell();
if(dia==null || mes==null || anio==null){
celdaFecha = new PdfPCell(new Paragraph("FECHA: " + strFecha,fuente2));
}else{
celdaFecha = new PdfPCell(new Paragraph("FECHA: " + dia + "/" + mes + "/" + anio,fuente2));
}
celdaFecha.setColspan(3); // Indicamos cuantas columnas ocupa la celda
celdaFecha.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaFecha);
//Celda en blanco
tableExterior.addCell(celdaLibre);
PdfPCell cellCab1 = new PdfPCell(new Phrase("NOMBRE PACIENTE",fuente5));
cellCab1.setBorder(PdfPCell.NO_BORDER);
//cellCab1.setBackgroundColor(BaseColor.GRAY);
tableExterior.addCell(cellCab1);
PdfPCell cellCab2 = new PdfPCell(new Phrase("ACTO REALIZADO",fuente5));
cellCab2.setBorder(PdfPCell.NO_BORDER);
// cellCab2.setBackgroundColor(BaseColor.GRAY);
tableExterior.addCell(cellCab2);
PdfPCell cellCab3 = new PdfPCell(new Phrase("IMPORTE",fuente5));
cellCab3.setBorder(PdfPCell.NO_BORDER);
//cellCab3.setBackgroundColor(BaseColor.GRAY);
tableExterior.addCell(cellCab3);
//Celda en blanco
tableExterior.addCell(celdaLibre2);
//AÑADIR PACIENTE
//Definicion de variables
String strParametroMenu="";
StringBuffer strSql = new StringBuffer();
int intPagina = 0;
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat(PersistenciaParametros.formatoFechas);
Object aCondiciones[]=null;
String[] arrFecha = strFecha.split("-");
java.sql.Date dtFecha = new java.sql.Date(java.sql.Date.valueOf(arrFecha[2] + "-" + arrFecha[1] + "-" + arrFecha[0]).getTime());
strSql.append("SELECT tamovext.fecha, tamovext.precio as precioActoMedico, ttactmed.descripcion as descripcionActoMedico, ttclient.nombre, ttclient.apellidos");
strSql.append(" FROM tamovext, ttactmed, ttbenefi, ttclient");
strSql.append(" WHERE tamovext.acto=ttactmed.acto");
strSql.append(" and tamovext.especialidad=ttactmed.especialidad");
strSql.append(" and tamovext.medico=?");
strSql.append(" and tamovext.especialidad=?");
strSql.append(" and tamovext.colectivo=ttbenefi.colectivo");
strSql.append(" and tamovext.poliza=ttbenefi.poliza");
strSql.append(" and tamovext.orden=ttbenefi.orden");
strSql.append(" and tamovext.entidad=ttbenefi.entidad");
strSql.append(" and ttbenefi.CLIENTE=ttclient.CLIENTE");
strSql.append(" and ttbenefi.fecha_baja is null");
strSql.append(" and tamovext.fecha=?");
strSql.append(" ORDER BY tamovext.fecha");
aCondiciones = new Object[3];
aCondiciones[0] = Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getMedico() );
aCondiciones[1] = Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad() );
aCondiciones[2] = dtFecha;
PersistenciaVTamovextTaclient per = new PersistenciaVTamovextTaclient();
Vector vSeleccion = per.seleccionar(strSql.toString(), 0, aCondiciones);
VTamovextTaclient vTamovextTaclient = null;
double dblImporteTotal = 0;
for(int i = 0; i < vSeleccion.size(); i++)
{
vTamovextTaclient = (VTamovextTaclient)vSeleccion.elementAt(i);
dblImporteTotal += vTamovextTaclient.getPrecioActoMedico();
PdfPCell cell1 = new PdfPCell(new Phrase(vTamovextTaclient.getApellidos(),fuente2));
cell1.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell1);
PdfPCell cell2 = new PdfPCell(new Phrase(vTamovextTaclient.getDescripcionActoMedico(),fuente2));
cell2.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell2);
PdfPCell cell3 = new PdfPCell(new Phrase(Utilidades.formatearDouble(vTamovextTaclient.getPrecioActoMedico(),PersistenciaParametros.decimales),fuente2));
cell3.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell3);
//
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
PdfPCell celdaImporteTotal = new PdfPCell(new Paragraph(" IMPORTE TOTAL " + Utilidades.formatearDouble(dblImporteTotal,PersistenciaParametros.decimales),fuente6));
celdaImporteTotal.setColspan(3); // Indicamos cuantas columnas ocupa la celda
celdaImporteTotal.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaImporteTotal);
document.add(tableExterior);
//CERRAR DOCUMENTO
// step 5: we close the document
document.close();
} catch (Exception ex) {
LogTarisan.logger.log(NivelLog.ERROR, "Error!!"+ex);
System.out.println("Excepcion" + ex);
}
}
private void generarPDFDetalleFechas (HttpServletRequest request, HttpServletResponse response, HttpSession sesion) throws ExcepcionTarisan
{
String strTexto = "";
try
{
//Creamos el documento
Document document = new Document();
//Fijamos Márgenes
document.setMargins(40, 40, 5, 5);
/*String strFile = "/root/apache-tomcat-6.0.20/webapps/tarisan/peticiones/DetallePaciente_" + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";*/
String strFile = ParametrosConfiguracion.ruta_pdf_peticiones_detalle_pacientes + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + ".pdf";
LogTarisan.logger.log(NivelLog.DEBUG, "Vamos a generar el PDF del detalle de pacientes");
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
// step 3: we open the document
document.open();
Print print = new Print();
//Definicion Fuentes
Font fuente1= new Font();
fuente1.setSize(18);
fuente1.setStyle(Font.BOLD);
Font fuente2= new Font();
fuente2.setSize(9);
Font fuente3= new Font();
fuente3.setSize(5);
Font fuente4= new Font();
fuente4.setSize(10);
fuente4.setStyle(Font.BOLD);
Font fuente5= new Font();
fuente5.setSize(9);
fuente5.setStyle(Font.BOLD);
Font fuente6= new Font();
fuente6.setSize(8);
fuente6.setStyle(Font.BOLD);
//Definicion Celda en blanco
PdfPCell celdaLibre = new PdfPCell(new Paragraph(" ",fuente1));
celdaLibre.setColspan(4); // Indicamos cuantas columnas ocupa la celda
celdaLibre.setBorder(PdfPCell.NO_BORDER);
PdfPCell celdaLibre2 = new PdfPCell(new Paragraph(" ",fuente3));
celdaLibre2.setColspan(4); // Indicamos cuantas columnas ocupa la celda
celdaLibre2.setBorder(PdfPCell.NO_BORDER);
//Definición de la tabla exterior
PdfPTable tableExterior = new PdfPTable(4); //Numero de comlumnas de la tabla
tableExterior.setWidthPercentage(100);
float[] headerWidths={80,260,250,70}; //Tamaño(Anchura) de las columnas
tableExterior.setWidths(headerWidths);
//Para que por defecto todas sus celdas salgan sin borde: tableExterior.getDefaultCell().setBorder(Rectangle.NO_BORDER);
int pos = 0; // Variable en la que guardamos la posicion que utilizamos para ajustar textos a la derecha
//AÑADIR LOGOTIPO
int intMedico=((Usuario)sesion.getAttribute("USUARIO")).getMedico();
document = print.anadirLogotipo(document, intMedico,45,780);
//AÑADIR CABECERA
strTexto = "Impresión Detalle Pacientes";
String strFecha = "";
String dia="";
String mes="";
String anio="";
if (request.getParameter("fecha") != null) {
strFecha = request.getParameter("fecha");
dia = strFecha.substring(0, 2);
mes = strFecha.substring(3, 5);
anio = strFecha.substring(6, 10);
//strFecha = dia+"/"+mes+"/"+anio;
//strFecha = strFecha.replaceAll("-", "/");
}
String strFechaHasta = "";
String diaHasta="";
String mesHasta="";
String anioHasta="";
if (request.getParameter("fechaHasta") != null) {
strFechaHasta = request.getParameter("fechaHasta");
diaHasta = strFechaHasta.substring(0, 2);
mesHasta = strFechaHasta.substring(3, 5);
anioHasta = strFechaHasta.substring(6, 10);
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
// Si desea crear una celda de mas de una columna. Cree un objecto Cell y cambie su propiedad span
PdfPCell celdaTitulo = new PdfPCell(new Paragraph(" " + strTexto,fuente1));
celdaTitulo.setColspan(4); // Indicamos cuantas columnas ocupa la celda
celdaTitulo.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTitulo);
//Celda en blanco
tableExterior.addCell(celdaLibre);
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("RELACIÓN ACTOS MÉDICOS REALIZADOS",fuente5));
celdaSubTitulo.setColspan(4); // Indicamos cuantas columnas ocupa la celda
//celdaSubTitulo.setBorder(PdfPCell.NO_BORDER);
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
//Celda en blanco
tableExterior.addCell(celdaLibre2);
PdfPCell celdaFecha = new PdfPCell();
if(dia==null || mes==null || anio==null){
celdaFecha = new PdfPCell(new Paragraph("FECHA DESDE: " + strFecha,fuente2));
}else{
celdaFecha = new PdfPCell(new Paragraph("FECHA DESDE: " + dia + "/" + mes + "/" + anio,fuente2));
}
celdaFecha.setColspan(4); // Indicamos cuantas columnas ocupa la celda
celdaFecha.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaFecha);
PdfPCell celdaFechaHasta = new PdfPCell();
if(diaHasta==null || mesHasta==null || anioHasta==null){
celdaFechaHasta = new PdfPCell(new Paragraph("FECHA HASTA: " + strFechaHasta,fuente2));
}else{
celdaFechaHasta = new PdfPCell(new Paragraph("FECHA HASTA: " + diaHasta + "/" + mesHasta + "/" + anioHasta,fuente2));
}
celdaFechaHasta.setColspan(4); // Indicamos cuantas columnas ocupa la celda
celdaFechaHasta.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaFechaHasta);
//Celda en blanco
tableExterior.addCell(celdaLibre);
PdfPCell cellCab0 = new PdfPCell(new Phrase("FECHA",fuente5));
cellCab0.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cellCab0);
PdfPCell cellCab1 = new PdfPCell(new Phrase("NOMBRE PACIENTE",fuente5));
cellCab1.setBorder(PdfPCell.NO_BORDER);
//cellCab1.setBackgroundColor(BaseColor.GRAY);
tableExterior.addCell(cellCab1);
PdfPCell cellCab2 = new PdfPCell(new Phrase("ACTO REALIZADO",fuente5));
cellCab2.setBorder(PdfPCell.NO_BORDER);
// cellCab2.setBackgroundColor(BaseColor.GRAY);
tableExterior.addCell(cellCab2);
PdfPCell cellCab3 = new PdfPCell(new Phrase("IMPORTE",fuente5));
cellCab3.setBorder(PdfPCell.NO_BORDER);
//cellCab3.setBackgroundColor(BaseColor.GRAY);
tableExterior.addCell(cellCab3);
//Celda en blanco
tableExterior.addCell(celdaLibre2);
//AÑADIR PACIENTE
//Definicion de variables
String strParametroMenu="";
StringBuffer strSql = new StringBuffer();
int intPagina = 0;
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat(PersistenciaParametros.formatoFechas);
Object aCondiciones[]=null;
String[] arrFecha = strFecha.split("-");
String[] arrFechaHasta = strFechaHasta.split("-");
java.sql.Date dtFecha = new java.sql.Date(java.sql.Date.valueOf(arrFecha[2] + "-" + arrFecha[1] + "-" + arrFecha[0]).getTime());
java.sql.Date dtFechaHasta = new java.sql.Date(java.sql.Date.valueOf(arrFechaHasta[2] + "-" + arrFechaHasta[1] + "-" + arrFechaHasta[0]).getTime());
strSql.append("SELECT tamovext_espia.fecha, tamovext_espia.precio as precioActoMedico, ttactmed.descripcion as descripcionActoMedico, ttclient.nombre, ttclient.apellidos");
strSql.append(" FROM tamovext_espia, ttactmed, ttbenefi, ttclient");
strSql.append(" WHERE tamovext_espia.acto=ttactmed.acto");
strSql.append(" and tamovext_espia.especialidad=ttactmed.especialidad");
strSql.append(" and tamovext_espia.medico=?");
strSql.append(" and tamovext_espia.especialidad=?");
strSql.append(" and tamovext_espia.borrado=0");
strSql.append(" and tamovext_espia.colectivo=ttbenefi.colectivo");
strSql.append(" and tamovext_espia.poliza=ttbenefi.poliza");
strSql.append(" and tamovext_espia.orden=ttbenefi.orden");
strSql.append(" and tamovext_espia.entidad=ttbenefi.entidad");
strSql.append(" and ttbenefi.CLIENTE=ttclient.CLIENTE");
/*strSql.append(" and ttbenefi.fecha_baja is null");*/
strSql.append(" and tamovext_espia.fecha>=?");
strSql.append(" and tamovext_espia.fecha<=?");
strSql.append(" and tamovext_espia.fecha>= ADD_MONTHS(TO_DATE(TRUNC(SYSDATE, 'MM')),-2)");
strSql.append(" ORDER BY tamovext_espia.fecha");
aCondiciones = new Object[4];
aCondiciones[0] = Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getMedico() );
aCondiciones[1] = Integer.valueOf( ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad() );
aCondiciones[2] = dtFecha;
aCondiciones[3] = dtFechaHasta;
PersistenciaVTamovextTaclient per = new PersistenciaVTamovextTaclient();
Vector vSeleccion = per.seleccionar(strSql.toString(), 0, aCondiciones);
VTamovextTaclient vTamovextTaclient = null;
double dblImporteTotal = 0;
for(int i = 0; i < vSeleccion.size(); i++)
{
vTamovextTaclient = (VTamovextTaclient)vSeleccion.elementAt(i);
dblImporteTotal += vTamovextTaclient.getPrecioActoMedico();
PdfPCell cell0 = new PdfPCell(new Phrase((vTamovextTaclient.getFecha()).toString(),fuente2));
cell0.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell0);
PdfPCell cell1 = new PdfPCell(new Phrase(vTamovextTaclient.getApellidos(),fuente2));
cell1.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell1);
PdfPCell cell2 = new PdfPCell(new Phrase(vTamovextTaclient.getDescripcionActoMedico(),fuente2));
cell2.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell2);
PdfPCell cell3 = new PdfPCell(new Phrase(Utilidades.formatearDouble(vTamovextTaclient.getPrecioActoMedico(),PersistenciaParametros.decimales),fuente2));
cell3.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(cell3);
//
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
PdfPCell celdaImporteTotal = new PdfPCell(new Paragraph(" IMPORTE TOTAL " + Utilidades.formatearDouble(dblImporteTotal,PersistenciaParametros.decimales),fuente6));
celdaImporteTotal.setColspan(4); // Indicamos cuantas columnas ocupa la celda
celdaImporteTotal.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaImporteTotal);
document.add(tableExterior);
//CERRAR DOCUMENTO
// step 5: we close the document
document.close();
} catch (Exception ex) {
LogTarisan.logger.log(NivelLog.ERROR, "Error!!"+ex);
System.out.println("Excepcion" + ex);
}
}
private void generarPDF(HttpServletRequest request, HttpServletResponse response, HttpSession sesion, int tipoDoc) throws ExcepcionTarisan
{
String strTexto = "";
LogTarisan.logger.log(NivelLog.DEBUG, "generarPDF - Empieza - TipoDoc: "+tipoDoc);
try
{
String strMedico = ((Usuario)sesion.getAttribute("USUARIO")).getNombreCab().toString();
String strDireccion = ((Usuario)sesion.getAttribute("USUARIO")).getDireccionCab().toString();
String strEspecialidad = ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidadCab().toString();
String strPoblacion = ((Usuario)sesion.getAttribute("USUARIO")).getPoblacionCab();
String strNumColegiado = "Num. Colegiado: " + ((Usuario)sesion.getAttribute("USUARIO")).getColegiadoCab().toString();
String strTelefono = ((Usuario)sesion.getAttribute("USUARIO")).getTelefonoCab().toString();
String strIngreso = (String)request.getParameter("num_ingreso");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 191");
SimpleDateFormat sdfFormateadorFecha=new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
String strMensajeSinElementos="No ha seleccionado ningún acto médico.";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 195");
// ArrayList que contedrá las descripciones de analíticas
ArrayList arrayListaElementosPrescripcion = null;
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 198");
//Arraylist que tiene el número de actos...
ArrayList arrayListaUnidades = new ArrayList();
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 201");
String strAutorizacion = "";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 204: request.getAttribute(\"autorizacion\") = "+request.getAttribute("autorizacion"));
if (request.getAttribute("modifiAuto") != null && request.getAttribute("modifiAuto").toString().compareTo("")!=0) {
if (request.getAttribute("modifiAuto") != null) {
if(request.getAttribute("modifiAuto").getClass() == Long.class)
{
strAutorizacion = String.valueOf(request.getAttribute("modifiAuto"));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 210: strAutorizacion"+strAutorizacion);
}
else
{
strAutorizacion = (String)request.getAttribute("modifiAuto");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 215: strAutorizacion"+strAutorizacion);
}
}
}else{
if (request.getAttribute("autorizacion") != null) {
if(request.getAttribute("autorizacion").getClass() == Long.class)
{
strAutorizacion = String.valueOf(request.getAttribute("autorizacion"));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 210: strAutorizacion"+strAutorizacion);
}
else
{
strAutorizacion = (String)request.getAttribute("autorizacion");
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 215: strAutorizacion"+strAutorizacion);
}
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 219");
String strInforme = "";
if (request.getParameter("informePrescripcion") != null) {
strInforme =(String)request.getParameter("informePrescripcion");
}
else if(request.getParameter("diagnostico") != null)
{
strInforme = (String)request.getParameter("diagnostico");
}
String strListaElementosPrescripcion = "";
String strListaElementosPrescripcionAux = "";
String strListaUnidades = "";
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 233");
if (request.getParameter("listaElementosPrescripcion") != null ) {
// Lista de elementos de Prescripción
LogTarisan.logger.log(NivelLog.DEBUG, "Se van a insertar los siguientes codigos de analitica: "+(String)request.getParameter("listaCodigoElementosPrescripcion"));
strListaElementosPrescripcion = (String)request.getParameter("listaElementosPrescripcion");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
}
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
strListaElementosPrescripcionAux = strListaElementosPrescripcion.replace('\'', '~');
}
strListaElementosPrescripcion = strListaElementosPrescripcionAux;
while(strListaElementosPrescripcion.indexOf("~") != -1) {
strListaElementosPrescripcion = strListaElementosPrescripcion.replace('~','\'');
}
// Vector vElementosPrescripcion = new Vector();
arrayListaElementosPrescripcion = new ArrayList();
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 246");
if (strListaElementosPrescripcion != null && strListaElementosPrescripcion.length() > 0) {
// Lista no vacía
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
//Separamos las diferentes determinaciones
int i = 0;
while (strListaElementosPrescripcion.indexOf("¬") != -1) {
arrayListaElementosPrescripcion.add(strListaElementosPrescripcion.substring(0, strListaElementosPrescripcion.indexOf("¬")));
strListaElementosPrescripcion = strListaElementosPrescripcion.substring(strListaElementosPrescripcion.indexOf("¬") + 1);
i++;
}
if (i==0){
arrayListaElementosPrescripcion.add(strListaElementosPrescripcion);
}
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 259");
ArrayList temp = new ArrayList();
strListaUnidades = (String)request.getParameter("unidadesElementosPrescripcion");
if(strListaUnidades != null)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 261"+strListaUnidades);
strListaUnidades = strListaUnidades.substring(1);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 264");
while(strListaUnidades.indexOf("¬") != -1)
{
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 267");
arrayListaUnidades.add(strListaUnidades.substring(0, strListaUnidades.indexOf("¬")));
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 269: - "+strListaUnidades.substring(0, strListaUnidades.indexOf("¬")));
strListaUnidades = strListaUnidades.substring(strListaUnidades.indexOf("¬") + 1);
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 271");
}
LogTarisan.logger.log(NivelLog.DEBUG, "Llega 274");
for(int i = 0; i<arrayListaElementosPrescripcion.size(); i++)
{
temp.add(arrayListaElementosPrescripcion.get(i) + " - Uds: " + arrayListaUnidades.get(i));
}
arrayListaElementosPrescripcion = temp;
}
}
Collections.sort(arrayListaElementosPrescripcion);
String strListaCodigoElementos = "";
if (request.getParameter("listaCodigoElementosPrescripcion")!=null) {
strListaCodigoElementos=(String)request.getParameter("listaCodigoElementosPrescripcion");
}
//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 (tipoDoc == OPC_PAC_PRESCRIPCION_FACTURACION) {
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_facturas + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() + "_" + ((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza() + ".pdf";
//strFile = Utilidades.Nombre_fact_pdf(((Usuario)sesion.getAttribute("USUARIO")).getMedico(), 1);
} else if ( tipoDoc == OPC_PAC_PRESCRIPCION_RECETAS)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_recetas + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() /*+ "_" + ((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza() */+ ".pdf";
} else if (tipoDoc == OPC_PAC_VOLANTE_INGRESO)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_ingresos + ((Usuario)sesion.getAttribute("USUARIO")).getMedico() /*+ "_" + ((Tarjeta)((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta()).getPoliza()*/ +".pdf";
}else if ( tipoDoc == OPC_PAC_PRESCRIPCION_DIAGNOSTICO)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_rx + strAutorizacion + ".pdf";
} else if ( tipoDoc == OPC_PAC_PRESCRIPCION_ANALITICA)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_analiticas + strAutorizacion + ".pdf";
} else if (tipoDoc == OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_ap + strAutorizacion + ".pdf";
}else if ( tipoDoc == OPC_PAC_PRESCRIPCION_ESPECIALIDADES)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_especialidades + strAutorizacion + ".pdf";
}else if (tipoDoc == OPC_PAC_PRESCRIPCION_ATS)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_ats + strAutorizacion + ".pdf";
}else if (tipoDoc == OPC_PAC_PETICION_AUTORIZACION)
{
strFile = ParametrosConfiguracion.ruta_pdf_peticiones_autorizaciones + strAutorizacion + ".pdf";
}else {
/*strFile = ParametrosConfiguracion.ruta_pdf + strAutorizacion + ".pdf";*/
/*strFile = "/root/peticiones/" + strAutorizacion + ".pdf";*/
strFile = "/var/lib/tomcat/webapps/tarisan/peticiones/" + strAutorizacion + ".pdf";
}
FileOutputStream foStream = new FileOutputStream(strFile);
PdfWriter writer = PdfWriter.getInstance(document,foStream);
document.open();
//Definicion Fuentes
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(20);
Font fuente2= new Font(raleway);
fuente2.setSize(11);
Font fuente5= new Font(ralewayNegrita);
fuente5.setSize(11);
//Definicion Celda en blanco
PdfPCell celdaLibre = new PdfPCell(new Paragraph(" ",fuente1));
celdaLibre.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaLibre.setBorder(PdfPCell.NO_BORDER);
//Creamos el objeto generador de PDF
Print print = new Print();
//AÑADIR CABECERA
switch(tipoDoc){
case OPC_PAC_PRESCRIPCION_DIAGNOSTICO:
{
strTexto = "Petición diagnóstico";
break;
}
case OPC_PAC_PRESCRIPCION_ANALITICA:
{
strTexto = "Petición Analítica";
break;
}
case OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA:
{
strTexto = "Petición Anatomía Patológica";
break;
}
case OPC_PAC_PRESCRIPCION_FACTURACION:
{
strTexto = "Impresión Facturación";
break;
}
case OPC_PAC_PETICION_AUTORIZACION:
{
strTexto = "Petición Autorización";
break;
}
case OPC_PAC_PRESCRIPCION_ESPECIALIDADES:
{
strTexto = "Impresión Especialidades";
break;
}
case OPC_PAC_PRESCRIPCION_RECETAS:
{
strTexto = "Impresión Recetas";
break;
}
case OPC_PAC_VOLANTE_INGRESO:
{
strTexto = "Autorización";
break;
}
case OPC_PAC_PRESCRIPCION_ATS:
{
strTexto = "Actos ATS";
break;
}
}
//AÑADIR LOGOTIPO
int intMedico=((Usuario)sesion.getAttribute("USUARIO")).getMedico();
document = print.anadirLogotipo(document, intMedico,45,780);
//Definición de la tabla exterior
PdfPTable tableExterior = new PdfPTable(2); //Numero de comlumnas de la tabla
tableExterior.setWidthPercentage(100);
float[] headerWidths={750,350}; //Tamaño(Anchura) de las columnas
tableExterior.setWidths(headerWidths);
tableExterior.getDefaultCell().setBorder(Rectangle.NO_BORDER);
tableExterior.addCell(celdaLibre);
PdfPCell celdaTitulo = new PdfPCell(new Paragraph(" " + strTexto,fuente1));
celdaTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaTitulo.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaTitulo);
//Celda en blanco
tableExterior.addCell(celdaLibre);
tableExterior.addCell(celdaLibre);
//AÑADIR MEDICOPRESCRIPTOR
if (tipoDoc != OPC_PAC_PRESCRIPCION_FACTURACION) {
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("Médico",fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
PdfPTable tableMedicoI = new PdfPTable(1);
tableMedicoI.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
tableMedicoI.addCell(new Paragraph(strMedico,fuente2));
tableMedicoI.addCell(new Paragraph(strEspecialidad,fuente2));
tableMedicoI.addCell(new Paragraph(strNumColegiado,fuente2));
tableExterior.addCell(tableMedicoI);
PdfPTable tableMedicoD = new PdfPTable(1);
tableMedicoD.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
tableMedicoD.addCell(new Paragraph(strDireccion,fuente2));
tableMedicoD.addCell(new Paragraph(strPoblacion,fuente2));
tableMedicoD.addCell(new Paragraph(strTelefono,fuente2));
tableExterior.addCell(tableMedicoD);
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
//AÑADIR PACIENTE
String strNomPaciente = "";
String strColectivo = "";
String strBeneficiario = "";
String strPoliza = "";
PersistenciaPaciente per = new PersistenciaPaciente();
String strfecnac = "00/00/0000";
Calendar fecnac = Calendar.getInstance();
String strnif = "";
if(sesion.getAttribute("PACIENTE") == null)
{
LogTarisan.logger.log(NivelLog.DEBUG, "No hay paciente en sesión, lo cojemos de los parámetros.");
strNomPaciente = (String)request.getParameter("nom_paciente");
LogTarisan.logger.log(NivelLog.DEBUG, "354");
strPoliza = (String)request.getParameter("poliza");
LogTarisan.logger.log(NivelLog.DEBUG, "356");
Tarjeta tar = new Tarjeta();
LogTarisan.logger.log(NivelLog.DEBUG, "358"+(String)request.getParameter("tarjeta"));
tar.setTarjeta(Integer.valueOf((String)request.getParameter("tarjeta")));
LogTarisan.logger.log(NivelLog.DEBUG, "360");
fecnac = per.obtenerFechaNacimiento(tar,((Usuario)sesion.getAttribute("USUARIO")).getMedico());
if(fecnac != null)
strfecnac = fecnac.get(Calendar.DAY_OF_MONTH)+"/"+(fecnac.get(Calendar.MONTH)+1)+"/"+fecnac.get(Calendar.YEAR);
strnif = per.obtenerNIF(tar,((Usuario)sesion.getAttribute("USUARIO")).getMedico());
}
else
{
strNomPaciente = ((Paciente)sesion.getAttribute("PACIENTE")).getNombre();
strColectivo = Long.toString( ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo());
strBeneficiario = Integer.toString(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario());
strPoliza = ((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getColectivo() +" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getPoliza()+" - "+((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta().getBeneficiario();
fecnac = per.obtenerFechaNacimiento(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
if(fecnac != null)
strfecnac = fecnac.get(Calendar.DAY_OF_MONTH)+"/"+(fecnac.get(Calendar.MONTH)+1)+"/"+fecnac.get(Calendar.YEAR);
strnif = per.obtenerNIF(((Paciente)sesion.getAttribute("PACIENTE")).getTarjeta(),((Usuario)sesion.getAttribute("USUARIO")).getMedico());
}
sdfFormateadorFecha = new SimpleDateFormat("dd/MM/yyyy");
dtFecha = new java.sql.Date(Calendar.getInstance().getTime().getTime());
strPoblacion += ", " + sdfFormateadorFecha.format(dtFecha);
int posicionY = 0;
//IMPRIMIR PACIENTE
if (tipoDoc == OPC_PAC_PRESCRIPCION_FACTURACION || tipoDoc == OPC_PAC_PRESCRIPCION_RECETAS) {
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("Paciente",fuente5));
celdaSubTitulo.setColspan(3); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
PdfPTable tablePacienteI = new PdfPTable(2);
tablePacienteI.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
tablePacienteI.addCell(new Paragraph(strNomPaciente,fuente2));
tablePacienteI.addCell(new Paragraph("",fuente2));
}
if (strPoblacion != null && strPoblacion.length() > 0) {
tablePacienteI.addCell(new Paragraph(strPoblacion,fuente2));
tablePacienteI.addCell(new Paragraph("",fuente2));
}
if (strnif != null && strnif.length() > 0) {
tablePacienteI.addCell(new Paragraph(strnif,fuente2));
tablePacienteI.addCell(new Paragraph("",fuente2));
}
tableExterior.addCell(tablePacienteI);
PdfPTable tablePacienteD = new PdfPTable(1);
tablePacienteD.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strPoliza != null && strPoliza.length() > 0) {
tablePacienteD.addCell(new Paragraph(strPoliza,fuente2));
}
if (strfecnac != null && strfecnac.length() > 0) {
tablePacienteD.addCell(new Paragraph("Fecha Nacimiento: "+strfecnac,fuente2));
}
tableExterior.addCell(tablePacienteD);
} else if (tipoDoc == OPC_PAC_PETICION_AUTORIZACION || tipoDoc == OPC_PAC_PRESCRIPCION_ATS) {
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("Paciente",fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
PdfPTable tablePacienteI = new PdfPTable(1);
tablePacienteI.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
tablePacienteI.addCell(new Paragraph(strNomPaciente,fuente2));
}
if (strAutorizacion != null && strAutorizacion.length() > 0) {
tablePacienteI.addCell(new Paragraph("Num. Solicitud: " + strAutorizacion,fuente2));
}
tableExterior.addCell(tablePacienteI);
PdfPTable tablePacienteD = new PdfPTable(1);
tablePacienteD.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strPoliza != null && strPoliza.length() > 0) {
tablePacienteD.addCell(new Paragraph(strPoliza,fuente2));
}
if (strPoblacion != null && strPoblacion.length() > 0) {
tablePacienteD.addCell(new Paragraph(strPoblacion,fuente2));
}
tableExterior.addCell(tablePacienteD);
} else if (tipoDoc == OPC_PAC_VOLANTE_INGRESO){
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("Paciente",fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
PdfPTable tablePacienteI = new PdfPTable(1);
tablePacienteI.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
tablePacienteI.addCell(new Paragraph(strNomPaciente,fuente2));
}
if (strPoblacion != null && strPoblacion.length() > 0) {
tablePacienteI.addCell(new Paragraph(strPoblacion,fuente2));
}
tableExterior.addCell(tablePacienteI);
PdfPTable tablePacienteD = new PdfPTable(1);
tablePacienteD.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strPoliza != null && strPoliza.length() > 0) {
tablePacienteD.addCell(new Paragraph(strPoliza,fuente2));
}
tableExterior.addCell(tablePacienteD);
}
else {
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph("Paciente",fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
PdfPTable tablePacienteI = new PdfPTable(1);
tablePacienteI.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strNomPaciente != null && strNomPaciente.length() > 0) {
tablePacienteI.addCell(new Paragraph(strNomPaciente,fuente2));
}
if (strAutorizacion != null && strAutorizacion.length() > 0) {
tablePacienteI.addCell(new Paragraph("Num. Solicitud: " + strAutorizacion,fuente2));
}
tableExterior.addCell(tablePacienteI);
PdfPTable tablePacienteD = new PdfPTable(1);
tablePacienteD.getDefaultCell().setBorder(PdfPCell.NO_BORDER);
if (strPoliza != null && strPoliza.length() > 0) {
tablePacienteD.addCell(new Paragraph(strPoliza,fuente2));
}
if (strPoblacion != null && strPoblacion.length() > 0) {
tablePacienteD.addCell(new Paragraph(strPoblacion,fuente2));
}
tableExterior.addCell(tablePacienteD);
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
//AÑADIR ANALISIS/RECETAS/
switch(tipoDoc){
case OPC_PAC_PRESCRIPCION_DIAGNOSTICO:
{
strTexto = "Ruego faciliten las siguientes pruebas:";
break;
}
case OPC_PAC_PRESCRIPCION_ANALITICA:
{
strTexto = "Ruego faciliten los siguientes análisis:";
break;
}
case OPC_PAC_PRESCRIPCION_ANATOMIA_PATOLOGICA:
{
strTexto = "Ruego faciliten las siguientes pruebas:";
break;
}
case OPC_PAC_PRESCRIPCION_FACTURACION:
{
strTexto = "Asistencia prestada:";
break;
}
case OPC_PAC_PETICION_AUTORIZACION:
{
strTexto = "Ruego faciliten la autorización de las siguientes pruebas:";
break;
}
case OPC_PAC_PRESCRIPCION_ATS:
{
strTexto = "Ruego realicen los siguientes actos:";
break;
}
case OPC_PAC_PRESCRIPCION_ESPECIALIDADES:
{
strTexto = "Ruego autoricen la asistencia a la especialidad:";
break;
}
case OPC_PAC_PRESCRIPCION_RECETAS:
{
strTexto = "DP./";
break;
}
case OPC_PAC_VOLANTE_INGRESO:
{
strTexto = "Solicito el siguiente ingreso:";
break;
}
}
//IMPRIMIR ANALISIS
if(tipoDoc != OPC_PAC_VOLANTE_INGRESO){
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph(strTexto,fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
String determinacion = "";
for (int i=0;i<arrayListaElementosPrescripcion.size();i++) {
if (arrayListaElementosPrescripcion.get(i) != null) {
determinacion = (String)arrayListaElementosPrescripcion.get(i);
}
if (determinacion.length() > 0) {
determinacion = determinacion.replaceAll(" ", "");
PdfPCell celdaPrescripcion = new PdfPCell(new Paragraph(determinacion,fuente2));
celdaPrescripcion.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaPrescripcion.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaPrescripcion);
}
}
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
if(tipoDoc == OPC_PAC_VOLANTE_INGRESO)
{
String strInformeCabecera = "Detalles del ingreso";
PersistenciaTtactmed perta = new PersistenciaTtactmed();
String detalle = "Motivo: "+ perta.obtenerDescripcionMotivoIngreso(Integer.parseInt(request.getParameter("motivo_ingreso")))+", acto a realizar: "+perta.obtenerNombreActo(Integer.parseInt(request.getParameter("acto_medico")), ((Usuario)sesion.getAttribute("USUARIO")).getEspecialidad());
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph(strInformeCabecera,fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
if (detalle != null && detalle.length() > 0) {
PdfPCell celdaDetalle = new PdfPCell(new Paragraph(detalle,fuente2));
celdaDetalle.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaDetalle.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaDetalle);
}
strTexto = "Informe médico";
celdaSubTitulo = new PdfPCell(new Paragraph(strTexto,fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
if (strInforme != null && strInforme.length() > 0) {
PdfPCell celdaInforme = new PdfPCell(new Paragraph(strInforme,fuente2));
celdaInforme.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaInforme.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaInforme);
}
}
else if (tipoDoc != OPC_PAC_PRESCRIPCION_FACTURACION && tipoDoc != OPC_PAC_PRESCRIPCION_RECETAS) {
strTexto = "Informe médico";
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph(strTexto,fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
if (strInforme != null && strInforme.length() > 0) {
PdfPCell celdaInforme = new PdfPCell(new Paragraph(strInforme,fuente2));
celdaInforme.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaInforme.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaInforme);
}
}
//Celda en blanco
tableExterior.addCell(celdaLibre);
if (tipoDoc == OPC_PAC_PRESCRIPCION_RECETAS) {
strTexto = "Informe/Posología";
PdfPCell celdaSubTitulo = new PdfPCell(new Paragraph(strTexto,fuente5));
celdaSubTitulo.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaSubTitulo.setBorder(Rectangle.BOTTOM);
tableExterior.addCell(celdaSubTitulo);
if (strInforme != null && strInforme.length() > 0) {
PdfPCell celdaInforme = new PdfPCell(new Paragraph(strInforme,fuente2));
celdaInforme.setColspan(2); // Indicamos cuantas columnas ocupa la celda
celdaInforme.setBorder(PdfPCell.NO_BORDER);
tableExterior.addCell(celdaInforme);
}
}
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());
}
}
}