Search in sources :

Example 1 with CX

use of ca.uhn.hl7v2.model.v25.datatype.CX in project streamsx.health by IBMStreams.

the class AdtToModelMapper method messageToModel.

@SuppressWarnings("unchecked")
public <T> Iterable<T> messageToModel(Message message) {
    ArrayList<ADTEvent> adtEvents = new ArrayList<ADTEvent>();
    if (message instanceof ADT_AXX) {
        ADT_AXX superMsg = (ADT_AXX) message;
        MessageInfo msg = new MessageInfo();
        Patient patient = new Patient();
        try {
            MSH header = superMsg.getMSH();
            msg.setSendingApp(header.getSendingApplication().encode());
            msg.setSendingFacility(header.getSendingFacility().encode());
            msg.setReceivingApp(header.getReceivingApplication().encode());
            msg.setReceivingFacility(header.getReceivingFacility().encode());
            msg.setMessageTs(header.getDateTimeOfMessage().encode());
            msg.setMessageType(header.getMessageType().encode());
            PID pid = superMsg.getPID();
            patient.setId(pid.getPatientID().encode());
            XPN[] patientNames = pid.getPatientName();
            for (XPN name : patientNames) {
                if (patient.getName().equals(IInjestServicesConstants.EMPTYSTR)) {
                    patient.setName(getPatientFullName(name));
                } else {
                    patient.addAlternateName(getPatientFullName(name));
                }
            }
            patient.setGender(pid.getAdministrativeSex().encode());
            patient.setDateOfBirth(pid.getDateTimeOfBirth().encode());
            CX[] ids = pid.getAlternatePatientIDPID();
            if (ids.length > 0) {
                for (CX cx : ids) {
                    patient.addAlternativeId(cx.encode());
                }
            }
            EventDetails evt = new EventDetails();
            EVN evn = superMsg.getEVN();
            evt.setEventType(evn.getEventTypeCode().encode());
            evt.setEventTs(evn.getEvn6_EventOccurred().encode());
            evt.setRecordTs(evn.getEvn2_RecordedDateTime().encode());
            PV1 pv1 = superMsg.getPV1();
            PatientVisit patientVisit = new PatientVisit();
            patientVisit.setPatientClass(pv1.getPatientClass().encode());
            patientVisit.setLocation(pv1.getAssignedPatientLocation().encode());
            patientVisit.setPriorLocation(pv1.getPriorPatientLocation().encode());
            patientVisit.setVisitNumber(pv1.getVisitNumber().encode());
            patient.setStatus(pv1.getBedStatus().encode());
            XCN[] doctors = pv1.getAttendingDoctor();
            for (XCN xcn : doctors) {
                String id = xcn.getIDNumber().encode();
                String name = xcn.getFamilyName().encode() + " " + xcn.getGivenName().encode();
                Clinician clinician = new Clinician();
                clinician.setId(id);
                clinician.setName(name);
                patientVisit.addAttendingDoctor(clinician);
            }
            doctors = pv1.getConsultingDoctor();
            for (XCN xcn : doctors) {
                String id = xcn.getIDNumber().encode();
                String name = xcn.getFamilyName().encode() + " " + xcn.getGivenName().encode();
                Clinician clinician = new Clinician();
                clinician.setId(id);
                clinician.setName(name);
                patientVisit.addConsultingDoctor(clinician);
            }
            ADTEvent adtEvent = new ADTEvent();
            adtEvent.setEvt(evt);
            adtEvent.setPatient(patient);
            adtEvent.setMsg(msg);
            adtEvent.setPv(patientVisit);
            adtEvents.add(adtEvent);
        } catch (HL7Exception e) {
            TRACE.error("Unable to parse HL7 message", e);
        }
    }
    return (Iterable<T>) adtEvents;
}
Also used : PatientVisit(com.ibm.streamsx.health.ingest.types.model.PatientVisit) XCN(ca.uhn.hl7v2.model.v26.datatype.XCN) MSH(ca.uhn.hl7v2.model.v26.segment.MSH) ADTEvent(com.ibm.streamsx.health.ingest.types.model.ADTEvent) ArrayList(java.util.ArrayList) Patient(com.ibm.streamsx.health.ingest.types.model.Patient) PID(ca.uhn.hl7v2.model.v26.segment.PID) PV1(ca.uhn.hl7v2.model.v26.segment.PV1) MessageInfo(com.ibm.streamsx.health.ingest.types.model.MessageInfo) EventDetails(com.ibm.streamsx.health.ingest.types.model.EventDetails) Clinician(com.ibm.streamsx.health.ingest.types.model.Clinician) CX(ca.uhn.hl7v2.model.v26.datatype.CX) XPN(ca.uhn.hl7v2.model.v26.datatype.XPN) HL7Exception(ca.uhn.hl7v2.HL7Exception) ADT_AXX(ca.uhn.hl7v2.model.v26.message.ADT_AXX) EVN(ca.uhn.hl7v2.model.v26.segment.EVN)

Example 2 with CX

use of ca.uhn.hl7v2.model.v25.datatype.CX in project openmrs-core by openmrs.

the class ORUR01Handler method createEncounter.

/**
 * This method does not call the database to create the encounter row. The encounter is only
 * created after all obs have been attached to it Creates an encounter pojo to be attached
 * later. This method does not create an encounterId
 *
 * @param msh
 * @param patient
 * @param pv1
 * @param orc
 * @return
 * @throws HL7Exception
 */
private Encounter createEncounter(MSH msh, Patient patient, PV1 pv1, ORC orc) throws HL7Exception {
    // the encounter we will return
    Encounter encounter;
    // look for the encounter id in PV1-19
    CX visitNumber = pv1.getVisitNumber();
    Integer encounterId = null;
    try {
        encounterId = Integer.valueOf(visitNumber.getIDNumber().getValue());
    } catch (NumberFormatException e) {
    // pass
    }
    // the database
    if (encounterId != null) {
        encounter = Context.getEncounterService().getEncounter(encounterId);
    } else {
        // if no encounter_id was passed in, this is a new
        // encounter, create the object
        encounter = new Encounter();
        Date encounterDate = getEncounterDate(pv1);
        Provider provider = getProvider(pv1);
        Location location = getLocation(pv1);
        Form form = getForm(msh);
        EncounterType encounterType = getEncounterType(msh, form);
        User enterer = getEnterer(orc);
        // Date dateEntered = getDateEntered(orc); // ignore this since we have no place in the data model to store it
        encounter.setEncounterDatetime(encounterDate);
        if (unknownRole == null) {
            unknownRole = Context.getEncounterService().getEncounterRoleByUuid(EncounterRole.UNKNOWN_ENCOUNTER_ROLE_UUID);
        }
        encounter.setProvider(unknownRole, provider);
        encounter.setPatient(patient);
        encounter.setLocation(location);
        encounter.setForm(form);
        encounter.setEncounterType(encounterType);
        encounter.setCreator(enterer);
        encounter.setDateCreated(new Date());
    }
    return encounter;
}
Also used : User(org.openmrs.User) CX(ca.uhn.hl7v2.model.v25.datatype.CX) Form(org.openmrs.Form) Encounter(org.openmrs.Encounter) EncounterType(org.openmrs.EncounterType) Date(java.util.Date) Provider(org.openmrs.Provider) Location(org.openmrs.Location)

Example 3 with CX

use of ca.uhn.hl7v2.model.v25.datatype.CX in project openmrs-core by openmrs.

the class HL7ServiceImpl method resolvePersonFromIdentifiers.

/**
 * @param identifiers CX identifier list from an identifier (either PID or NK1)
 * @return The internal id number of the Patient based on one of the given identifiers, or null
 *         if the patient is not found
 * @throws HL7Exception
 */
@Override
@Transactional(readOnly = true)
public Person resolvePersonFromIdentifiers(CX[] identifiers) throws HL7Exception {
    // give up if no identifiers exist
    if (identifiers.length < 1) {
        throw new HL7Exception("Missing patient identifier in PID segment");
    }
    // Take the first uniquely matching identifier
    for (CX identifier : identifiers) {
        String hl7PersonId = identifier.getIDNumber().getValue();
        // TODO if 1st component is blank, check 2nd and 3rd of assigning
        // authority
        String assigningAuthority = identifier.getAssigningAuthority().getNamespaceID().getValue();
        if (StringUtils.isNotBlank(assigningAuthority)) {
            // Assigning authority defined
            try {
                PatientIdentifierType pit = Context.getPatientService().getPatientIdentifierTypeByName(assigningAuthority);
                if (pit == null) {
                    // there is no matching PatientIdentifierType
                    if (assigningAuthority.equals(HL7Constants.HL7_AUTHORITY_UUID)) {
                        // the identifier is a UUID
                        Person p = Context.getPersonService().getPersonByUuid(hl7PersonId);
                        if (p != null) {
                            return p;
                        }
                        log.warn("Can't find person for UUID '" + hl7PersonId + "'");
                        // skip identifiers with unknown type
                        continue;
                    } else if (assigningAuthority.equals(HL7Constants.HL7_AUTHORITY_LOCAL)) {
                        // the ID is internal (local)
                        String idType = identifier.getIdentifierTypeCode().getValue();
                        try {
                            if (idType.equals(HL7Constants.HL7_ID_PERSON)) {
                                Integer pid = Integer.parseInt(hl7PersonId);
                                // patient_id == person_id, so just look for
                                // the person
                                Person p = Context.getPersonService().getPerson(pid);
                                if (p != null) {
                                    return p;
                                }
                            } else if (idType.equals(HL7Constants.HL7_ID_PATIENT)) {
                                Integer pid = Integer.parseInt(hl7PersonId);
                                // patient_id == person_id, so just look for
                                // the person
                                Patient p = Context.getPatientService().getPatient(pid);
                                if (p != null) {
                                    return p;
                                }
                            }
                        } catch (NumberFormatException e) {
                        }
                        log.warn("Can't find Local identifier of '" + hl7PersonId + "'");
                        // skip identifiers with unknown type
                        continue;
                    }
                    log.warn("Can't find PatientIdentifierType named '" + assigningAuthority + "'");
                    // skip identifiers with unknown type
                    continue;
                }
                List<PatientIdentifier> matchingIds = Context.getPatientService().getPatientIdentifiers(hl7PersonId, Collections.singletonList(pit), null, null, null);
                if (matchingIds == null || matchingIds.isEmpty()) {
                    // no matches
                    log.warn("NO matches found for " + hl7PersonId);
                    // try next identifier
                    continue;
                } else if (matchingIds.size() == 1) {
                    // unique match -- we're done
                    return matchingIds.get(0).getPatient();
                } else {
                    // ambiguous identifier
                    log.debug("Ambiguous identifier in PID. " + matchingIds.size() + " matches for identifier '" + hl7PersonId + "' of type '" + pit + "'");
                    // try next identifier
                    continue;
                }
            } catch (Exception e) {
                log.error("Error resolving patient identifier '" + hl7PersonId + "' for assigning authority '" + assigningAuthority + "'", e);
                continue;
            }
        } else {
            try {
                log.debug("CX contains ID '" + hl7PersonId + "' without assigning authority -- assuming patient.patient_id");
                return Context.getPatientService().getPatient(Integer.parseInt(hl7PersonId));
            } catch (NumberFormatException e) {
                log.warn("Invalid patient ID '" + hl7PersonId + "'");
            }
        }
    }
    return null;
}
Also used : CX(ca.uhn.hl7v2.model.v25.datatype.CX) HL7Exception(ca.uhn.hl7v2.HL7Exception) Patient(org.openmrs.Patient) Person(org.openmrs.Person) PatientIdentifierType(org.openmrs.PatientIdentifierType) PatientIdentifier(org.openmrs.PatientIdentifier) URISyntaxException(java.net.URISyntaxException) DAOException(org.openmrs.api.db.DAOException) FileNotFoundException(java.io.FileNotFoundException) APIException(org.openmrs.api.APIException) HL7Exception(ca.uhn.hl7v2.HL7Exception) EncodingNotSupportedException(ca.uhn.hl7v2.parser.EncodingNotSupportedException) IOException(java.io.IOException) PatientIdentifierException(org.openmrs.api.PatientIdentifierException) ApplicationException(ca.uhn.hl7v2.app.ApplicationException) Transactional(org.springframework.transaction.annotation.Transactional)

Example 4 with CX

use of ca.uhn.hl7v2.model.v25.datatype.CX in project openmrs-core by openmrs.

the class HL7ServiceImpl method getUuidFromIdentifiers.

/**
 * @see org.openmrs.hl7.HL7Service#getUuidFromIdentifiers(ca.uhn.hl7v2.model.v25.datatype.CX[])
 */
@Override
public String getUuidFromIdentifiers(CX[] identifiers) throws HL7Exception {
    Boolean found = false;
    String uuid = null;
    for (CX identifier : identifiers) {
        // check for UUID as the assigning authority
        if (OpenmrsUtil.nullSafeEquals(identifier.getAssigningAuthority().getNamespaceID().getValue(), "UUID")) {
            // check for duplicates
            if (found && !OpenmrsUtil.nullSafeEquals(identifier.getIDNumber().getValue(), uuid)) {
                throw new HL7Exception("multiple UUID values found");
            }
            uuid = identifier.getIDNumber().getValue();
            found = true;
        }
    }
    // returns null if not found
    return uuid;
}
Also used : CX(ca.uhn.hl7v2.model.v25.datatype.CX) HL7Exception(ca.uhn.hl7v2.HL7Exception)

Example 5 with CX

use of ca.uhn.hl7v2.model.v25.datatype.CX in project openmrs-core by openmrs.

the class HL7ServiceImpl method createPersonFromNK1.

/**
 * @see org.openmrs.hl7.HL7Service#createPersonFromNK1(ca.uhn.hl7v2.model.v25.segment.NK1)
 */
@Override
public Person createPersonFromNK1(NK1 nk1) throws HL7Exception {
    // NOTE: following block (with minor modifications) stolen from
    // ADTA28Handler
    // TODO: generalize this for use with both PID and NK1 segments
    Person person = new Person();
    // UUID
    CX[] identifiers = nk1.getNextOfKinAssociatedPartySIdentifiers();
    String uuid = getUuidFromIdentifiers(identifiers);
    if (Context.getPersonService().getPersonByUuid(uuid) != null) {
        throw new HL7Exception("Non-unique UUID '" + uuid + "' for new person");
    }
    person.setUuid(uuid);
    // Patient Identifiers
    List<PatientIdentifier> goodIdentifiers = new ArrayList<>();
    for (CX id : identifiers) {
        String assigningAuthority = id.getAssigningAuthority().getNamespaceID().getValue();
        String hl7PatientId = id.getIDNumber().getValue();
        log.debug("identifier has id=" + hl7PatientId + " assigningAuthority=" + assigningAuthority);
        if (assigningAuthority != null && assigningAuthority.length() > 0) {
            try {
                PatientIdentifierType pit = Context.getPatientService().getPatientIdentifierTypeByName(assigningAuthority);
                if (pit == null) {
                    if (!"UUID".equals(assigningAuthority)) {
                        log.warn("Can't find PatientIdentifierType named '" + assigningAuthority + "'");
                    }
                    // skip identifiers with unknown type
                    continue;
                }
                PatientIdentifier pi = new PatientIdentifier();
                pi.setIdentifierType(pit);
                pi.setIdentifier(hl7PatientId);
                // Get default location
                Location location = Context.getLocationService().getDefaultLocation();
                if (location == null) {
                    throw new HL7Exception("Cannot find default location");
                }
                pi.setLocation(location);
                try {
                    PatientIdentifierValidator.validateIdentifier(pi);
                    goodIdentifiers.add(pi);
                } catch (PatientIdentifierException ex) {
                    log.warn("Patient identifier in NK1 is invalid: " + pi, ex);
                }
            } catch (Exception e) {
                log.error("Uncaught error parsing/creating patient identifier '" + hl7PatientId + "' for assigning authority '" + assigningAuthority + "'", e);
            }
        } else {
            log.debug("NK1 contains identifier with no assigning authority");
            continue;
        }
    }
    if (!goodIdentifiers.isEmpty()) {
        // If we have one identifier, set it as the preferred to make the validator happy.
        if (goodIdentifiers.size() == 1) {
            goodIdentifiers.get(0).setPreferred(true);
        }
        // cast the person as a Patient and add identifiers
        person = new Patient(person);
        ((Patient) person).addIdentifiers(goodIdentifiers);
    }
    // Person names
    for (XPN patientNameX : nk1.getNKName()) {
        PersonName name = new PersonName();
        name.setFamilyName(patientNameX.getFamilyName().getSurname().getValue());
        name.setGivenName(patientNameX.getGivenName().getValue());
        name.setMiddleName(patientNameX.getSecondAndFurtherGivenNamesOrInitialsThereof().getValue());
        person.addName(name);
    }
    // Gender (checks for null, but not for 'M' or 'F')
    String gender = nk1.getAdministrativeSex().getValue();
    if (gender == null) {
        throw new HL7Exception("Missing gender in an NK1 segment");
    }
    gender = gender.toUpperCase();
    if (!OpenmrsConstants.GENDER().containsKey(gender)) {
        throw new HL7Exception("Unrecognized gender: " + gender);
    }
    person.setGender(gender);
    // Date of Birth
    TS dateOfBirth = nk1.getDateTimeOfBirth();
    if (dateOfBirth == null || dateOfBirth.getTime() == null || dateOfBirth.getTime().getValue() == null) {
        throw new HL7Exception("Missing birth date in an NK1 segment");
    }
    person.setBirthdate(HL7Util.parseHL7Timestamp(dateOfBirth.getTime().getValue()));
    // Estimated birthdate?
    ID precisionTemp = dateOfBirth.getDegreeOfPrecision();
    if (precisionTemp != null && precisionTemp.getValue() != null) {
        String precision = precisionTemp.getValue().toUpperCase();
        log.debug("The birthdate is estimated: " + precision);
        if ("Y".equals(precision) || "L".equals(precision)) {
            person.setBirthdateEstimated(true);
        }
    }
    // save the new person or patient
    if (person instanceof Patient) {
        Context.getPatientService().savePatient((Patient) person);
    } else {
        Context.getPersonService().savePerson(person);
    }
    return person;
}
Also used : PersonName(org.openmrs.PersonName) ArrayList(java.util.ArrayList) Patient(org.openmrs.Patient) PatientIdentifier(org.openmrs.PatientIdentifier) URISyntaxException(java.net.URISyntaxException) DAOException(org.openmrs.api.db.DAOException) FileNotFoundException(java.io.FileNotFoundException) APIException(org.openmrs.api.APIException) HL7Exception(ca.uhn.hl7v2.HL7Exception) EncodingNotSupportedException(ca.uhn.hl7v2.parser.EncodingNotSupportedException) IOException(java.io.IOException) PatientIdentifierException(org.openmrs.api.PatientIdentifierException) ApplicationException(ca.uhn.hl7v2.app.ApplicationException) CX(ca.uhn.hl7v2.model.v25.datatype.CX) XPN(ca.uhn.hl7v2.model.v25.datatype.XPN) HL7Exception(ca.uhn.hl7v2.HL7Exception) ID(ca.uhn.hl7v2.model.v25.datatype.ID) PID(ca.uhn.hl7v2.model.v25.segment.PID) Person(org.openmrs.Person) PatientIdentifierType(org.openmrs.PatientIdentifierType) PatientIdentifierException(org.openmrs.api.PatientIdentifierException) Location(org.openmrs.Location) TS(ca.uhn.hl7v2.model.v25.datatype.TS)

Aggregations

CX (ca.uhn.hl7v2.model.v25.datatype.CX)10 HL7Exception (ca.uhn.hl7v2.HL7Exception)5 Message (ca.uhn.hl7v2.model.Message)5 ORU_R01 (ca.uhn.hl7v2.model.v25.message.ORU_R01)5 NK1 (ca.uhn.hl7v2.model.v25.segment.NK1)5 Test (org.junit.Test)5 ORUR01Handler (org.openmrs.hl7.handler.ORUR01Handler)5 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)5 ApplicationException (ca.uhn.hl7v2.app.ApplicationException)3 ArrayList (java.util.ArrayList)3 Location (org.openmrs.Location)3 Patient (org.openmrs.Patient)3 PatientIdentifier (org.openmrs.PatientIdentifier)3 PatientIdentifierType (org.openmrs.PatientIdentifierType)3 PatientIdentifierException (org.openmrs.api.PatientIdentifierException)3 ID (ca.uhn.hl7v2.model.v25.datatype.ID)2 TS (ca.uhn.hl7v2.model.v25.datatype.TS)2 XPN (ca.uhn.hl7v2.model.v25.datatype.XPN)2 PID (ca.uhn.hl7v2.model.v25.segment.PID)2 EncodingNotSupportedException (ca.uhn.hl7v2.parser.EncodingNotSupportedException)2