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

Java tutorial

Introduction

Here is the source code for com.dominion.salud.mpr.negocio.service.tratamientos.impl.AdministracionesServiceImpl.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.group.RAS_O17_ORDER;
import ca.uhn.hl7v2.model.v25.message.RAS_O17;
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.RXA;
import ca.uhn.hl7v2.model.v25.segment.RXO;
import ca.uhn.hl7v2.model.v25.segment.TQ1;
import com.dominion.salud.mpr.hl7.er7.ER7Parser;
import com.dominion.salud.mpr.negocio.entities.admin.Centros;
import com.dominion.salud.mpr.negocio.entities.equivalencias.FormasFarExt;
import com.dominion.salud.mpr.negocio.entities.equivalencias.PautasExt;
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.Administraciones;
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.AdministracionesRepository;
import com.dominion.salud.mpr.negocio.service.admin.CentrosService;
import com.dominion.salud.mpr.negocio.service.equivalencias.FormasFarExtService;
import com.dominion.salud.mpr.negocio.service.equivalencias.PautasExtService;
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.AdministracionesService;
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("administracionesService")
public class AdministracionesServiceImpl extends AbstractTratamientosServiceImpl<Administraciones, Long>
        implements AdministracionesService {

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

    @Autowired
    private AdministracionesRepository administracionesRepository;

    @Autowired
    private CentrosService centrosService;
    @Autowired
    private SexosExtService sexosExtService;
    @Autowired
    private MedicosService medicosService;
    @Autowired
    private MarcasService marcasService;
    @Autowired
    private UnidMedExtService unidMedExtService;
    @Autowired
    private FormasFarExtService formasFarExtService;
    @Autowired
    private PautasExtService pautasExtService;
    @Autowired
    private SecuenciasExtService secuenciasExtService;
    @Autowired
    private PacientesService pacientesService;
    @Autowired
    private EpisodiosService episodiosService;
    @Autowired
    private PrescripcionesService prescripcionesService;

    @Override
    public Administraciones findByCodAdministracion(Administraciones administraciones) {
        return administracionesRepository.findByCodAdministracion(administraciones);
    }

    @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 {
            RAS_O17 hl7message = (RAS_O17) new ER7Parser().parse(message);

            PID pid = hl7message.getPATIENT().getPID();
            PV1 pv1 = hl7message.getPATIENT().getPATIENT_VISIT().getPV1();

            List<RAS_O17_ORDER> ras_o17_orders = hl7message.getORDERAll();
            for (RAS_O17_ORDER ras_o17_order : ras_o17_orders) {
                ORC orc = ras_o17_order.getORC();
                TQ1 tq1 = ras_o17_order.getTIMING().getTQ1();
                RXA rxa = ras_o17_order.getADMINISTRATION().getRXA();
                RXO rxo = ras_o17_order.getORDER_DETAIL().getRXO();

                //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.3.1 - Codigo de Administracion
                String cod_administracion = null;
                logger.debug("     Procesando CODIGO DE ADMINSTRACION ("
                        + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")"); //ORC.2.1
                if (StringUtils.isNotBlank(orc.getFillerOrderNumber().getEntityIdentifier().getValue())) {
                    cod_administracion = orc.getFillerOrderNumber().getEntityIdentifier().getValue();
                    logger.debug("          ORC.3.1 - Codigo de Administracion: " + cod_administracion);
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el campo ORC.3.1 - CODIGO DE ADMINSTRACION ("
                                    + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: CODIGO DE ADMINSTRACION ("
                                    + orc.getFillerOrderNumber().getEntityIdentifier().getValue() + ")");
                }

                //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() + ")");
                }

                //RXA.3 - Fecha de la Administracion
                Date fecha_administracion = null;
                logger.debug("     Procesando FECHA DE LA ADMINISTRACION ("
                        + rxa.getDateTimeStartOfAdministration().getTime().getValue() + ")"); //RXA.3
                if (StringUtils.isNotBlank(rxa.getDateTimeStartOfAdministration().getTime().getValue())
                        && rxa.getDateTimeStartOfAdministration().getTime().getValueAsDate() != null) {
                    fecha_administracion = rxa.getDateTimeStartOfAdministration().getTime().getValueAsDate();
                    logger.debug("          RXA.3 - Fecha de la Administracion: " + fecha_administracion);
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el CAMPO RXD.3 - FECHA DE LA ADMINISTRACION ("
                                    + rxa.getDateTimeStartOfAdministration().getTime().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: FECHA DE LA ADMINISTRACION ("
                                    + rxa.getDateTimeStartOfAdministration().getTime().getValue() + ")");
                }

                //RXA.5 - Marca
                logger.debug("     Procesando de la MARCA (" + rxa.getAdministeredCode().getIdentifier().getValue()
                        + ") " + rxa.getAdministeredCode().getText().getValue());
                Marcas marcas = new Marcas();
                marcas.setCodNac(rxa.getAdministeredCode().getIdentifier().getValue()); //RXA.5.1
                marcas.setTxtMarca(rxa.getAdministeredCode().getText().getValue()); //RXA.5.2
                marcas = marcasService.findByCodNacAndInsert(marcas);
                if (marcas != null) {
                    logger.debug("          RXA.5 - Marca: " + marcas.toString());
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el CAMPO RXA.5 - MARCA ("
                                    + rxa.getAdministeredCode().getIdentifier().getValue() + ") "
                                    + rxa.getAdministeredCode().getText().getValue());
                    resultado.add("No se puede procesar el movimiento sin INFORMACION en el CAMPO: MARCA ("
                            + rxa.getAdministeredCode().getIdentifier().getValue() + ") "
                            + rxa.getAdministeredCode().getText().getValue());
                }

                //RXA.6 - Dosis Administrada en Forma Farmaceutica
                Double dosis_administrada = null;
                logger.debug("     Procesando datos de la DOSIS ADMINISTRADA ("
                        + rxa.getAdministeredAmount().getValue() + ")"); //RXA.6
                if (StringUtils.isNotBlank(rxa.getAdministeredAmount().getValue())
                        && NumberUtils.isNumber(rxa.getAdministeredAmount().getValue())) {
                    try {
                        dosis_administrada = NumberUtils.createDouble(rxa.getAdministeredAmount().getValue());
                        logger.debug("          RXA.6 - Dosis Administrada: " + dosis_administrada);
                    } catch (Exception e) {
                        logger.error(
                                "          No se puede procesar el movimiento porque la INFORMACION en el CAMPO RXA.6 - DOSIS ADMINISTRADA ("
                                        + rxa.getAdministeredAmount().getValue() + ") NO es correcta");
                        resultado.add(
                                "No se puede procesar el movimiento porque la INFORMACION en el CAMPO: DOSIS ADMINISTRADA ("
                                        + rxa.getAdministeredAmount().getValue() + ") NO es correcta");
                    }
                } else {
                    logger.error(
                            "          No se puede procesar el movimiento sin INFORMACION en el CAMPO RXA.6 - Dosis Administrada ("
                                    + rxa.getAdministeredAmount().getValue() + ")");
                    resultado.add(
                            "No se puede procesar el movimiento sin INFORMACION en el CAMPO: Dosis Administrada ("
                                    + rxa.getAdministeredAmount().getValue() + ")");
                }

                //RXA.7 - Forma Farmaceutica de la Dosis Administrada
                logger.debug("     Procesando la FORMA FARMACEUTICA DE LA DOSIS ADMINISTRADA ("
                        + rxa.getAdministeredUnits().getIdentifier().getValue() + ") "
                        + rxa.getAdministeredUnits().getText().getValue());
                FormasFarExt formasFarExt = new FormasFarExt();
                try {
                    formasFarExt.setCentros(centros);
                    formasFarExt.setCodFormaFarExt(rxa.getAdministeredUnits().getIdentifier().getValue()); //RXA.7.1
                    formasFarExt.setTxtFormaFarExt(rxa.getAdministeredUnits().getText().getValue()); //RXA.7.2
                    formasFarExt = formasFarExtService.traducirEquivalenciaAndInsert(formasFarExt);
                    logger.debug("          RXA.7 - Forma Farmaceutica de la Dosis Administrada: "
                            + formasFarExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(rxa.getAdministeredUnits().getIdentifier().getValue())) {
                        logger.warn(
                                "               No se ha indicado INFORMACION para el CAMPO RXA.7 - FORMA FARMACEUTICA DE LA DOSIS ADMINISTRADA ("
                                        + rxa.getAdministeredUnits().getIdentifier().getValue() + ") "
                                        + rxa.getAdministeredUnits().getText().getValue());
                    } else {
                        logger.warn(
                                "               No se ha encontrado EQUIVALENCIA para el CAMPO RXA.7 - FORMA FARMACEUTICA DE LA DOSIS ADMINISTRADA ("
                                        + rxa.getAdministeredUnits().getIdentifier().getValue() + ") "
                                        + rxa.getAdministeredUnits().getText().getValue());
                    }
                }

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

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

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

                //RXO.4 - Unidad de Medida de la Dosis Prescrita
                logger.debug("     Procesando datos de la UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                        + rxo.getRequestedGiveUnits().getIdentifier().getValue() + ") "
                        + rxo.getRequestedGiveUnits().getText().getValue());
                UnidMedExt unidMedExt = new UnidMedExt();
                try {
                    unidMedExt.setCentros(centros);
                    unidMedExt.setCodUnidMedExt(rxo.getRequestedGiveUnits().getIdentifier().getValue()); //Z01.10.1
                    unidMedExt.setTxtUnidMedExt(rxo.getRequestedGiveUnits().getText().getValue()); //Z01.10.2
                    unidMedExt = unidMedExtService.traducirEquivalenciaAndInsert(unidMedExt);
                    logger.debug(
                            "          RXO.4 - Unidad de Medida de la Dosis Prescrita: " + unidMedExt.toString());
                } catch (NoExisteEquivalenciaException neee) {
                    if (StringUtils.isNotBlank(rxo.getRequestedGiveUnits().getIdentifier().getValue())) {
                        logger.warn(
                                "               No se ha indicado INFORMACION para el CAMPO RXO.4 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                        + rxo.getRequestedGiveUnits().getIdentifier().getValue() + ") "
                                        + rxo.getRequestedGiveUnits().getText().getValue());
                    } else {
                        logger.warn(
                                "               No se ha encontrado EQUIVALENCIA para el CAMPO RXO.4 - UNIDAD DE MEDIDA DE LA DOSIS PRESCRITA ("
                                        + rxo.getRequestedGiveUnits().getIdentifier().getValue() + ") "
                                        + rxo.getRequestedGiveUnits().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
                Prescripciones prescripciones = new Prescripciones();
                try {
                    prescripciones.setCodPrescripcion(cod_prescripcion);
                    logger.debug("     Buscando PRESCRIPCION por COD_PRESCRIPCION ("
                            + prescripciones.getCodPrescripcion() + ")");
                    prescripciones = prescripcionesService.findByCodPrescripcion(prescripciones);
                } catch (NoResultException nre) {
                    logger.debug("          Almacenando datos de la PRESCRIPCION: (" + cod_prescripcion + ")");
                    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 = prescripcionesService
                            .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());
                            prescripcionesService.save(prescripcionesUpd);
                        }
                    }

                    prescripciones.setEpisodios(episodios);
                    prescripciones.setMarcas(marcas);
                    prescripciones.setMedicos(medicos);
                    prescripciones.setDosis(dosis_prescrita);
                    prescripciones.setFechaIni(fecha_ini_prescripcion);
                    prescripciones.setPautas(pautasExt.getPautas());
                    prescripciones.setSecuencias(secuenciasExt.getSecuencias());
                    prescripciones.setCodPrescripcion(cod_prescripcion);
                    prescripciones.setUnidMed(unidMedExt.getUnidMed());
                    prescripciones = prescripcionesService.save(prescripciones);
                } finally {
                    logger.debug("          Prescripcion: " + prescripciones.toString());
                }

                //ADMINISTRACIONES
                Administraciones administraciones = new Administraciones();
                try {
                    administraciones.setCodAdministracion(cod_administracion);
                    logger.debug("     Buscando ADMINISTRACIONES por COD_ADMINISTRACION ("
                            + administraciones.getCodAdministracion() + ")");
                    administraciones = findByCodAdministracion(administraciones);
                } catch (NoResultException nre) {
                    administraciones.setPrescripciones(prescripciones);
                    administraciones.setFormasFar(formasFarExt.getFormasFar());
                    administraciones.setCantidad(dosis_administrada);
                    administraciones.setFechaAdm(fecha_administracion);
                    save(administraciones);
                } finally {
                    logger.debug("          Administraciones: " + administraciones.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());
        }
    }
}