com.dominion.salud.mpr.negocio.service.tratamientos.impl.PrescripcionesServiceImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.dominion.salud.mpr.negocio.service.tratamientos.impl.PrescripcionesServiceImpl.java

Source

/*
 * Copyright (C) 2016 Dominion Global
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.dominion.salud.mpr.negocio.service.tratamientos.impl;

import ca.uhn.hl7v2.model.v25.segment.ORC;
import ca.uhn.hl7v2.model.v25.segment.PID;
import ca.uhn.hl7v2.model.v25.segment.PV1;
import ca.uhn.hl7v2.model.v25.segment.RXC;
import ca.uhn.hl7v2.model.v25.segment.TQ1;
import com.dominion.salud.mpr.hl7.er7.ER7Parser;
import com.dominion.salud.mpr.hl7.v25.group.ZMP_O09_ORDER;
import com.dominion.salud.mpr.hl7.v25.message.ZMP_O09;
import com.dominion.salud.mpr.hl7.v25.segment.Z01;
import com.dominion.salud.mpr.negocio.entities.admin.Centros;
import com.dominion.salud.mpr.negocio.entities.equivalencias.PautasExt;
import com.dominion.salud.mpr.negocio.entities.equivalencias.RazonFinExt;
import com.dominion.salud.mpr.negocio.entities.equivalencias.SecuenciasExt;
import com.dominion.salud.mpr.negocio.entities.equivalencias.SexosExt;
import com.dominion.salud.mpr.negocio.entities.equivalencias.UnidMedExt;
import com.dominion.salud.mpr.negocio.entities.maestros.Marcas;
import com.dominion.salud.mpr.negocio.entities.maestros.Medicos;
import com.dominion.salud.mpr.negocio.entities.tratamientos.Episodios;
import com.dominion.salud.mpr.negocio.entities.tratamientos.Pacientes;
import com.dominion.salud.mpr.negocio.entities.tratamientos.Prescripciones;
import com.dominion.salud.mpr.negocio.repositories.tratamientos.PrescripcionesRepository;
import com.dominion.salud.mpr.negocio.service.admin.CentrosService;
import com.dominion.salud.mpr.negocio.service.equivalencias.PautasExtService;
import com.dominion.salud.mpr.negocio.service.equivalencias.RazonFinExtService;
import com.dominion.salud.mpr.negocio.service.equivalencias.SecuenciasExtService;
import com.dominion.salud.mpr.negocio.service.equivalencias.SexosExtService;
import com.dominion.salud.mpr.negocio.service.equivalencias.UnidMedExtService;
import com.dominion.salud.mpr.negocio.service.exception.NoExisteEquivalenciaException;
import com.dominion.salud.mpr.negocio.service.maestros.MarcasService;
import com.dominion.salud.mpr.negocio.service.maestros.MedicosService;
import com.dominion.salud.mpr.negocio.service.tratamientos.EpisodiosService;
import com.dominion.salud.mpr.negocio.service.tratamientos.PacientesService;
import com.dominion.salud.mpr.negocio.service.tratamientos.PrescripcionesService;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.NoResultException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 *
 * @author jcgonzalez
 */
@Service("prescripcionesService")
public class PrescripcionesServiceImpl extends AbstractTratamientosServiceImpl<Prescripciones, Long>
        implements PrescripcionesService {

    private static final Logger logger = LoggerFactory.getLogger(PrescripcionesServiceImpl.class);

    @Autowired
    private CentrosService centrosService;
    @Autowired
    private SexosExtService sexosExtService;
    @Autowired
    private SecuenciasExtService secuenciasExtService;
    @Autowired
    private PautasExtService pautasExtService;
    @Autowired
    private RazonFinExtService razonFinExtService;
    @Autowired
    private UnidMedExtService unidMedExtService;
    @Autowired
    private MedicosService medicosService;
    @Autowired
    private MarcasService marcasService;
    @Autowired
    private PacientesService pacientesService;
    @Autowired
    private EpisodiosService episodiosService;

    @Autowired
    private PrescripcionesRepository prescripcionesRepository;

    @Override
    public Prescripciones findByCodPrescripcion(Prescripciones prescripciones) {
        return prescripcionesRepository.findByCodPrescripcion(prescripciones);
    }

    @Override
    public List<Prescripciones> findLikeCodPrescripcion(Prescripciones prescripciones) {
        return prescripcionesRepository.findLikeCodPrescripcion(prescripciones);
    }

    /**
     *
     * @param message
     * @throws Exception
     */
    @Override
    @Transactional(noRollbackFor = { NoResultException.class })
    public void processMessage(String message) throws Exception {
        logger.info("INICIANDO EL PROCESADO DEL MOVIMIENTO ENTRANTE");
        logger.info(message);

        //Resultado final del proceso
        List<String> resultado = new ArrayList<>();

        try {
            ZMP_O09 hl7message = (ZMP_O09) new ER7Parser().parse(message);
            PID pid = hl7message.getPATIENT().getPID();
            PV1 pv1 = hl7message.getPATIENT().getPATIENT_VISIT().getPV1();

            List<ZMP_O09_ORDER> zmp_o09_orders = hl7message.getORDERAll();
            for (ZMP_O09_ORDER zmp_o09_order : zmp_o09_orders) {
                ORC orc = zmp_o09_order.getORC();
                Z01 z01 = zmp_o09_order.getZ01();
                TQ1 tq1 = zmp_o09_order.getTIMING().getTQ1();
                RXC rxc = zmp_o09_order.getCOMPONENT().getRXC();

                //ORC.21.10 - Centro
                logger.debug("     Procesando datos del CENTRO ("
                        + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ") "
                        + orc.getOrderingFacilityName(0).getOrganizationName().getValue());
                Centros centros = new Centros();
                centros.setCodCentro(orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue()); //ORC.21.10
                try {
                    centros = centrosService.findByCodCentro(centros);
                    logger.debug("          ORC.21.10 - Centro: " + centros.toString());
                } catch (NoResultException nre) {
                    logger.error(
                            "          No se puede procesar el movimiento sin EQUIVALENCIA para el campo ORC.21.10 - CENTRO ("
                                    + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ")");
                    resultado.add("No se puede procesar el movimiento sin EQUIVALENCIA para el CAMPO: CENTRO ("
                            + orc.getOrderingFacilityName(0).getOrganizationIdentifier().getValue() + ")");
                }

                //PID.3 - Identificadores del paciente (NHC) y (CIPA)
                Integer nhc = null;
                String cipa = null;
                logger.debug("     Procesando el campo PID.3 - Identificadores del Paciente");
                for (int i = 0; i < pid.getPatientIdentifierList().length; i++) { // PID.3 - PatientIdentifierList
                    if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "PI")) {
                        try {
                            nhc = NumberUtils
                                    .createInteger(pid.getPatientIdentifierList(i).getIDNumber().getValue());
                            logger.debug("               PID.3(PI): " + nhc);
                        } catch (Exception e) {
                            logger.warn("El campo PID.3(PI) - NHC ("
                                    + pid.getPatientIdentifierList(i).getIDNumber().getValue()
                                    + ") no es correcto");
                        }
                    } else if (StringUtils.equalsIgnoreCase(
                            pid.getPatientIdentifierList(i).getIdentifierTypeCode().getValue(), "CIPA")) {
                        if (StringUtils.isNotBlank(pid.getPatientIdentifierList(i).getIDNumber().getValue())) {
                            cipa = pid.getPatientIdentifierList(i).getIDNumber().getValue();
                            logger.debug("               PID.3(CIPA): " + cipa);
                        }
                    }
                }

                //PID.5 - Paciente
                logger.debug("     Procesando datos del PACIENTE ("
                        + pid.getPatientName(0).getFamilyName().getSurname().getValue() + " "
                        + pid.getMotherSMaidenName(0).getFamilyName().getSurname().getValue() + ", "
                        + pid.getPatientName(0).getGivenName().getValue() + ")");
                Pacientes pacientes = new Pacientes();
                pacientes.setCipa(cipa);
                pacientes.setTxtNombre(pid.getPatientName(0).getGivenName().getValue()); //PID.5.2
                pacientes.setTxtApellido1(pid.getPatientName(0).getFamilyName().getSurname().getValue()); //PID.5.1.1
                pacientes.setTxtApellido2(pid.getMotherSMaidenName(0).getFamilyName().getSurname().getValue()); //PID.6.1.1
                pacientes.setFechaNac(pid.getDateTimeOfBirth().getTime().getValueAsDate()); //PID.7.1
                logger.debug("          PID.5 - Paciente: " + pacientes.toString());

                //PID.8 - Sexo
                logger.debug("     Procesando datos del SEXO (" + pid.getAdministrativeSex().getValue() + ")");
                SexosExt sexosExt = new SexosExt();
                try {
                    sexosExt.setCentros(centros);
                    sexosExt.setCodSexoExt(pid.getAdministrativeSex().getValue()); //PID.8
                    sexosExt.setTxtSexoExt(pid.getAdministrativeSex().getValue()); //PID.8
                    sexosExt = sexosExtService.traducirEquivalencia(sexosExt);
                    logger.debug("          PID.8 - Sexo: " + sexosExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(pid.getAdministrativeSex().getValue())) {
                        logger.warn("          No se ha encontrado EQUIVALENCIA para el CAMPO PID.8 - SEXO ("
                                + pid.getAdministrativeSex().getValue() + ")");
                    } else {
                        logger.warn("          No se ha indicado INFORMACION para el CAMPO PID.8 - SEXO ("
                                + pid.getAdministrativeSex().getValue() + ")");
                    }
                }

                //Datos del Episodio
                Episodios episodios = new Episodios();
                //PV1.2 - Clase de Paciente
                logger.debug(
                        "     Procesando datos de la CLASE DE PACIENTE (" + pv1.getPatientClass().getValue() + ")"); //PV1.2
                if (StringUtils.isNotBlank(pv1.getPatientClass().getValue())) {
                    if (StringUtils.equals(pv1.getPatientClass().getValue(), "O")) { //Outpatient
                        //PV1.18 - Tipo de Paciente
                        logger.debug("          Procesando datos del TIPO DE PACIENTE ("
                                + pv1.getPatientType().getValue() + ")"); //PV1.18
                        if (StringUtils.isNotBlank(pv1.getPatientType().getValue())) {
                            episodios.setAmbito(pv1.getPatientType().getValue());
                        } else {
                            logger.error(
                                    "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.18 - TIPO DE PACIENTE ("
                                            + pv1.getPatientType().getValue() + ")");
                            resultado.add(
                                    "No se puede procesar el movimiento sin INFORMACION en el CAMPO: TIPO DE PACIENTE");
                        }
                    } else {
                        episodios.setAmbito("H");
                    }
                    logger.debug("          PV1.2 - Clase de Paciente y PV1.18 - Tipo de Paciente: "
                            + episodios.getAmbito());
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.2 - CLASE DE PACIENTE ("
                                    + pv1.getPatientClass().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CLASE DE PACIENTE");
                }

                //PV1.19.1 - Codigo de Episodio
                logger.debug("     Procesando datos del CODIGO DE EPISODIO ("
                        + pv1.getVisitNumber().getIDNumber().getValue() + ")"); //PV1.19.1
                if (StringUtils.isNotBlank(pv1.getVisitNumber().getIDNumber().getValue())) {
                    episodios.setCodEpisodio(pv1.getVisitNumber().getIDNumber().getValue());
                    logger.debug("          PV1.19.1 - Codigo de Episodio: " + episodios.getCodEpisodio());
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el CAMPO PV1.19.1 - CODIGO DE EPISODIO ("
                                    + pv1.getVisitNumber().getIDNumber().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE EPISODIO");
                }

                //ORC.2.1 - Codigo de Prescripcion
                String cod_prescripcion = null;
                logger.debug("     Procesando CODIGO DE PRESCRIPCION ("
                        + orc.getPlacerOrderNumber().getEntityIdentifier().getValue() + ")"); //ORC.2.1
                if (StringUtils.isNotBlank(orc.getPlacerOrderNumber().getEntityIdentifier().getValue())) {
                    cod_prescripcion = orc.getPlacerOrderNumber().getEntityIdentifier().getValue();
                    logger.debug("          ORC.2.1 - Codigo de Prescripcion: " + cod_prescripcion);
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el CAMPO ORC.2.1 - CODIGO DE PRESCRIPCION ("
                                    + orc.getPlacerOrderNumber().getEntityIdentifier().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE PRESCRIPCION");
                }

                //ORC.10 - Medico Prescriptor
                logger.debug("     Procesando datos del MEDICO PRESCRIPTOR ("
                        + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                        + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                        + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                        + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof().getValue());
                Medicos medicos = new Medicos();
                medicos.setCodMedico(orc.getEnteredBy(0).getIDNumber().getValue()); //ORC.10.1
                medicos.setTxtNombre(orc.getEnteredBy(0).getGivenName().getValue()); //ORC.10.3
                medicos.setTxtApellido1(orc.getEnteredBy(0).getFamilyName().getSurname().getValue()); //ORC.10.2.1
                medicos.setTxtApellido2(
                        orc.getEnteredBy(0).getSecondAndFurtherGivenNamesOrInitialsThereof().getValue()); //ORC.10.4
                medicos = medicosService.findByCodMedicoAndInsert(medicos);
                if (medicos != null) {
                    logger.debug("          ORC.10 - Medico Prescriptor: " + medicos.toString());
                } else {
                    logger.error(
                            "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: ORC.10 - MEDICO PRESCRIPTOR ("
                                    + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                                    + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                                    + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                                    + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof()
                                            .getValue());
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: MEDICO PRESCRIPTOR ("
                                    + orc.getEnteredBy(0).getIDNumber().getValue() + ") "
                                    + orc.getOrderingProvider(0).getGivenName().getValue() + " "
                                    + orc.getOrderingProvider(0).getFamilyName().getSurname().getValue() + " "
                                    + orc.getOrderingProvider(0).getSecondAndFurtherGivenNamesOrInitialsThereof()
                                            .getValue());
                }

                //TQ1.7 - Fecha de Inicio de la Prescripcion
                Date fecha_ini_prescripcion = null;
                logger.debug("     Procesando FECHA DE INICIO DE LA PRESCRIPCION ("
                        + tq1.getStartDateTime().getTime().getValue() + ")"); //TQ1.7
                if (StringUtils.isNotBlank(tq1.getStartDateTime().getTime().getValue())
                        && tq1.getStartDateTime().getTime().getValueAsDate() != null) {
                    fecha_ini_prescripcion = tq1.getStartDateTime().getTime().getValueAsDate();
                    logger.debug("          TQ1.7 - Fecha de Inicio de la Prescripcion: " + fecha_ini_prescripcion);
                } else {
                    logger.error(
                            "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: TQ1.7 - FECHA DE INICIO DE LA PRESCRIPCION ("
                                    + tq1.getStartDateTime().getTime().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA DE INICIO DE LA PRESCRIPCION ("
                                    + tq1.getStartDateTime().getTime().getValue() + ")");
                }

                //TQ1.8 - Fecha Fin de la Prescripcion
                Date fecha_fin_prescripcion = null;
                logger.debug("     Procesando FECHA DE FIN DE LA PRESCRIPCION ("
                        + tq1.getEndDateTime().getTime().getValue() + ")"); //TQ1.8
                if (StringUtils.isNotBlank(tq1.getEndDateTime().getTime().getValue())
                        && tq1.getEndDateTime().getTime().getValueAsDate() != null) {
                    fecha_fin_prescripcion = tq1.getEndDateTime().getTime().getValueAsDate();
                    logger.debug("          TQ1.8 - Fecha de Fin de la Prescripcion: " + fecha_fin_prescripcion);
                } else {
                    logger.error(
                            "               No se puede procesar el movimiento sin INFORMACION en el CAMPO: TQ1.8 - FECHA FIN DE LA PRESCRIPCION ("
                                    + tq1.getEndDateTime().getTime().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA FIN DE LA PRESCRIPCION ("
                                    + tq1.getEndDateTime().getTime().getValue() + ")");
                }

                //RXC.2 - Marca
                logger.debug("     Procesando de la MARCA (" + rxc.getComponentCode().getIdentifier().getValue()
                        + ") " + rxc.getComponentCode().getText().getValue());
                Marcas marcas = new Marcas();
                marcas.setCodNac(rxc.getComponentCode().getIdentifier().getValue()); //RXC.2.1
                marcas.setTxtMarca(rxc.getComponentCode().getText().getValue()); //RXC.2.2
                marcas = marcasService.findByCodNacAndInsert(marcas);
                if (marcas != null) {
                    logger.debug("          RXC.2 - Marca: " + marcas.toString());
                } else {
                    logger.error(
                            "               No se puede procesar el movimiento sin INFORMACION en el campo RXC.2 - MARCA ("
                                    + rxc.getComponentCode().getIdentifier().getValue() + ") "
                                    + rxc.getComponentCode().getText().getValue());
                    resultado.add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: MARCA ("
                            + rxc.getComponentCode().getIdentifier().getValue() + ") "
                            + rxc.getComponentCode().getText().getValue());
                }

                //Z01.9 - Dosis Prescrita en Unidad de Medida
                Double dosis_prescrita = null;
                logger.debug(
                        "     Procesando datos de la DOSIS PRESCRITA (" + z01.getDosisPrescrita().getValue() + ")"); //Z01.9
                if (StringUtils.isNotBlank(z01.getDosisPrescrita().getValue())
                        && NumberUtils.isNumber(z01.getDosisPrescrita().getValue())) {
                    try {
                        dosis_prescrita = NumberUtils.createDouble(z01.getDosisPrescrita().getValue());
                        logger.debug("          Z01.9 - Dosis Prescrita: " + dosis_prescrita);
                    } catch (Exception e) {
                        logger.error(
                                "          No se puede procesar el movimiento porque la INFORMACION en el campo Z01.9 - DOSIS PRESCRITA ("
                                        + z01.getDosisPrescrita().getValue() + ") NO es correcta");
                        resultado.add(
                                "No se puede procesar el movimiento porque la INFORMACION en el CAMPO: DOSIS PRESCRITA ("
                                        + z01.getDosisPrescrita().getValue() + ") NO es correcta");
                    }
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin datos en el campo Z01.9 - Dosis Prescrita ("
                                    + z01.getDosisPrescrita().getValue() + ")");
                    resultado
                            .add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: Dosis Prescrita ("
                                    + z01.getDosisPrescrita().getValue() + ")");
                }

                //Z01.10 - Unidad de Medida de la Dosis Prescrita
                logger.debug("     Procesando datos de la UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                        + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                        + z01.getUnidMedDosisPrescrita().getText().getValue());
                UnidMedExt unidMedExt = new UnidMedExt();
                try {
                    unidMedExt.setCentros(centros);
                    unidMedExt.setCodUnidMedExt(z01.getUnidMedDosisPrescrita().getIdentifier().getValue()); //Z01.10.1
                    unidMedExt.setTxtUnidMedExt(z01.getUnidMedDosisPrescrita().getText().getValue()); //Z01.10.2
                    unidMedExt = unidMedExtService.traducirEquivalenciaAndInsert(unidMedExt);
                    logger.debug(
                            "          Z01.10 - Unidad de Medida de la Dosis Prescrita: " + unidMedExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(z01.getUnidMedDosisPrescrita().getIdentifier().getValue())) {
                        logger.warn(
                                "               No se ha indicado INFORMACION para el CAMPO Z01.10 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                        + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                                        + z01.getUnidMedDosisPrescrita().getText().getValue());
                    } else {
                        logger.warn(
                                "               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.10 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                        + z01.getUnidMedDosisPrescrita().getIdentifier().getValue() + ") "
                                        + z01.getUnidMedDosisPrescrita().getText().getValue());
                    }
                }

                //Z01.13 - Secuencias
                logger.debug("     Procesando de la SECUENCIA (" + z01.getSecuencia().getIdentifier().getValue()
                        + ") " + z01.getSecuencia().getText().getValue());
                SecuenciasExt secuenciasExt = new SecuenciasExt();
                try {
                    secuenciasExt.setCentros(centros);
                    secuenciasExt.setCodSecuenciaExt(z01.getSecuencia().getIdentifier().getValue()); //Z01.13.1
                    secuenciasExt.setTxtSecuenciaExt(z01.getSecuencia().getText().getValue()); //Z01.13.2
                    secuenciasExt = secuenciasExtService.traducirEquivalenciaAndInsert(secuenciasExt);
                    logger.debug("          Z01.13 - Secuencia: " + secuenciasExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(z01.getSecuencia().getIdentifier().getValue())) {
                        logger.warn(
                                "               No se ha indicado INFORMACION para el CAMPO Z01.13 - SECUENCIA ("
                                        + z01.getSecuencia().getIdentifier().getValue() + ") "
                                        + z01.getSecuencia().getText().getValue());
                    } else {
                        logger.warn(
                                "               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.13 - SECUENCIA ("
                                        + z01.getSecuencia().getIdentifier().getValue() + ") "
                                        + z01.getSecuencia().getText().getValue());
                    }
                }

                //Z01.14 - Pautas
                logger.debug("     Procesando de la PAUTA (" + z01.getPauta().getIdentifier().getValue() + ") "
                        + z01.getPauta().getText().getValue());
                PautasExt pautasExt = new PautasExt();
                try {
                    pautasExt.setCentros(centros);
                    pautasExt.setCodPautaExt(z01.getPauta().getIdentifier().getValue()); //Z01.14.1
                    pautasExt.setTxtPautaExt(z01.getPauta().getText().getValue()); //Z01.14.2
                    pautasExt = pautasExtService.traducirEquivalenciaAndInsert(pautasExt);
                    logger.debug("          Z01.14 - Pauta: " + pautasExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(z01.getPauta().getIdentifier().getValue())) {
                        logger.warn("               No se ha indicado INFORMACION para el CAMPO Z01.14 - PAUTA ("
                                + z01.getPauta().getIdentifier().getValue() + ") "
                                + z01.getPauta().getText().getValue());
                    } else {
                        logger.warn("               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.14 - PAUTA ("
                                + z01.getPauta().getIdentifier().getValue() + ") "
                                + z01.getPauta().getText().getValue());
                    }
                }

                //Z01.16 - Razon Fin
                logger.debug("     Procesando la RAZON DE FIN DE TRATAMIENTO ("
                        + z01.getRazonFin().getIdentifier().getValue() + ") "
                        + z01.getRazonFin().getText().getValue());
                RazonFinExt razonFinExt = new RazonFinExt();
                try {
                    razonFinExt.setCentros(centros);
                    razonFinExt.setCodRazonFinExt(z01.getRazonFin().getIdentifier().getValue()); //Z01.16.1
                    razonFinExt.setTxtRazonFinExt(z01.getRazonFin().getText().getValue()); //Z01.16.2
                    razonFinExt = razonFinExtService.traducirEquivalenciaAndInsert(razonFinExt);
                    logger.debug("          Z01.16 - Razon de Fin: " + razonFinExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(z01.getRazonFin().getIdentifier().getValue())) {
                        logger.warn(
                                "               No se ha indicado INFORMACION para el CAMPO Z01.16 - RAZON DE FIN DE TRATAMIENTO ("
                                        + z01.getRazonFin().getIdentifier().getValue() + ") "
                                        + z01.getRazonFin().getText().getValue());
                    } else {
                        logger.warn(
                                "               No se ha encontrado EQUIVALENCIA para el CAMPO Z01.16 - RAZON DE FIN DE TRATAMIENTO ("
                                        + z01.getRazonFin().getIdentifier().getValue() + ") "
                                        + z01.getRazonFin().getText().getValue());
                    }
                }

                //RESULTADO GENERAL DEL PROCESADO DEL MOVIMIENTO
                String mensaje = "";
                if (!resultado.isEmpty()) {
                    logger.error("RESULTADO GENERAL DEL PROCESADO: ");
                    for (String linea : resultado) {
                        mensaje += "     - " + linea + "\n";
                    }
                    logger.error("     " + mensaje);
                }

                if (StringUtils.isNotBlank(mensaje)) {
                    throw new Exception(mensaje);
                }
                logger.info("FINALIZANDO EL PROCESADO DEL MOVIMIENTO ENTRANTE ENTRANTE");

                //ALMACENAMIENTO DEL MOVIMIENTO
                logger.info("INICIANDO EL ALMACENAMIENTO DEL MOVIMIENTO ENTRANTE");

                //PACIENTE
                try {
                    logger.debug("     Buscando PACIENTE por CIPA (" + pacientes.getCipa() + ")");
                    pacientes = pacientesService.findByCIPA(pacientes);
                } catch (NoResultException nre) {
                    logger.debug("          Almacenando datos del PACIENTE");
                    pacientes.setSexos(sexosExt.getSexos());
                    pacientes = pacientesService.save(pacientes);
                } finally {
                    logger.debug("          Paciente: " + pacientes.toString());
                }

                //EPISODIO
                try {
                    episodios.setNhc(nhc);
                    episodios.setCentros(centros);
                    episodios.setPacientes(pacientes);

                    logger.debug("     Buscando EPISODIO por COD_EPISODIO (" + episodios.getCodEpisodio()
                            + "), NHC (" + episodios.getNhc() + "), PROGRAMA (" + episodios.getProgramas()
                            + "), CENTRO (" + episodios.getCentros() + ")");
                    episodios = episodiosService.findByCodEpisodioNHCIdProgramaIdCentro(episodios);
                } catch (NoResultException nre) {
                    logger.debug("          Almacenando datos del EPISODIO");
                    episodios = episodiosService.save(episodios);
                } finally {
                    logger.debug("          Episodio: " + episodios.toString());
                }

                //PRESCRIPCIONES
                logger.debug("     Almacenando datos de la PRESCRIPCION: (" + cod_prescripcion + ")");
                Prescripciones prescripciones = new Prescripciones();
                try {
                    prescripciones.setCodPrescripcion(cod_prescripcion);
                    logger.debug("          Buscando PRESCRIPCION por COD_PRESCRIPCION ("
                            + prescripciones.getCodPrescripcion() + ")");
                    prescripciones = findByCodPrescripcion(prescripciones);

                    logger.debug("          Actualizando PRESCRIPCION por COD_PRESCRIPCION ("
                            + prescripciones.getCodPrescripcion() + ")");
                    prescripciones.setFechaFin(fecha_fin_prescripcion);
                    prescripciones.setRazonFin(razonFinExt.getRazonFin());
                    prescripciones = save(prescripciones);
                } catch (NoResultException nre) {
                    Prescripciones prescripcionesOld = new Prescripciones();
                    prescripcionesOld
                            .setCodPrescripcion(StringUtils.split(prescripciones.getCodPrescripcion(), "-")[0] + "-"
                                    + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[1] + "-"
                                    + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[2] + "-"
                                    + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[3] + "-"
                                    + StringUtils.split(prescripciones.getCodPrescripcion(), "-")[4]);
                    List<Prescripciones> prescripcioneses = findLikeCodPrescripcion(prescripcionesOld);
                    for (Prescripciones prescripcionesUpd : prescripcioneses) {
                        if (StringUtils.equals(StringUtils.split(prescripcionesUpd.getCodPrescripcion(), "-")[7],
                                StringUtils.split(prescripciones.getCodPrescripcion(), "-")[7])) {
                            logger.debug("               Estableciendo fecha de fin en la prescripcion: "
                                    + prescripcionesUpd.toString());
                            prescripcionesUpd.setFechaFin(new Date());
                            save(prescripcionesUpd);
                        }
                    }

                    prescripciones.setEpisodios(episodios);
                    prescripciones.setMarcas(marcas);
                    prescripciones.setMedicos(medicos);
                    prescripciones.setDosis(dosis_prescrita);
                    prescripciones.setFechaIni(fecha_ini_prescripcion);
                    prescripciones.setFechaFin(fecha_fin_prescripcion);
                    prescripciones.setRazonFin(razonFinExt.getRazonFin());
                    prescripciones.setCodPrescripcion(cod_prescripcion);
                    prescripciones.setPautas(pautasExt.getPautas());
                    prescripciones.setRazonFin(razonFinExt.getRazonFin());
                    prescripciones.setSecuencias(secuenciasExt.getSecuencias());
                    prescripciones.setUnidMed(unidMedExt.getUnidMed());
                    prescripciones = save(prescripciones);
                } finally {
                    logger.debug("          Prescripcion: " + prescripciones.toString());
                }
                logger.info("FINALIZANDO EL ALMACENAMIENTO DEL MOVIMIENTO ENTRANTE");
            }
        } catch (Exception e) {
            throw new Exception("SE HAN PRODUCIDO ERRORES AL PROCESAR EL MOVIMIENTO: \n" + e.getMessage() != null
                    ? e.getMessage()
                    : e.toString());
        }
    }
}