Search in sources :

Example 91 with Patient

use of org.openmrs.Patient 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)

Example 92 with Patient

use of org.openmrs.Patient in project openmrs-core by openmrs.

the class ADTA28Handler method processADT_A28.

private Message processADT_A28(ADT_A05 adt) throws HL7Exception {
    // validate HL7 version
    validate(adt);
    // extract segments for convenient use below
    MSH msh = getMSH(adt);
    PID pid = getPID(adt);
    // Obtain message control id (unique ID for message from sending
    // application). Eventually avoid replaying the same message.
    String messageControlId = msh.getMessageControlID().getValue();
    log.debug("Found HL7 message in inbound queue with control id = " + messageControlId);
    // Add creator of the patient to application
    String sendingApp = msh.getSendingApplication().getComponent(0).toString();
    log.debug("SendingApplication = " + sendingApp);
    // Search for the patient
    Integer patientId = findPatientId(pid);
    // Create new patient if the patient id doesn't exist yet
    if (patientId == null) {
        log.info("Creating new patient in response to ADT_A28 " + messageControlId);
        Patient patient = createPatient(pid, sendingApp);
        if (patient == null) {
            throw new HL7Exception("Couldn't create Patient object from PID");
        }
        Context.getPatientService().savePatient(patient);
    } else {
        log.info("Ignoring ADT_A28 message because patient (" + patientId + ") already exists.");
    }
    return adt;
}
Also used : MSH(ca.uhn.hl7v2.model.v25.segment.MSH) HL7Exception(ca.uhn.hl7v2.HL7Exception) Patient(org.openmrs.Patient) PID(ca.uhn.hl7v2.model.v25.segment.PID)

Example 93 with Patient

use of org.openmrs.Patient in project openmrs-core by openmrs.

the class HL7ServiceTest method processHL7Message_shouldSaveHl7MessageToTheDatabase.

/**
 * @throws HL7Exception
 * @see HL7Service#processHL7Message(Message)
 */
@Test
public void processHL7Message_shouldSaveHl7MessageToTheDatabase() throws HL7Exception {
    executeDataSet("org/openmrs/hl7/include/ORUTest-initialData.xml");
    HL7Service hl7service = Context.getHL7Service();
    Message message = hl7service.parseHL7String("MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||3^^^^||John3^Doe^||\r" + "PV1||O|1^Unknown Location||||1^Super User (1-8)|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT\r" + "OBX|1|NM|5497^CD4, BY FACS^99DCT||450|||||||||20080206\r" + "OBX|2|DT|5096^RETURN VISIT DATE^99DCT||20080229|||||||||20080212");
    Message result = hl7service.processHL7Message(message);
    Assert.assertNotNull(result);
    Concept returnVisitDateConcept = new Concept(5096);
    Calendar cal = Calendar.getInstance();
    cal.set(2008, Calendar.FEBRUARY, 29, 0, 0, 0);
    List<Obs> returnVisitDateObsForPatient3 = Context.getObsService().getObservationsByPersonAndConcept(new Patient(3), returnVisitDateConcept);
    assertEquals("There should be a return visit date", 1, returnVisitDateObsForPatient3.size());
}
Also used : Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) Message(ca.uhn.hl7v2.model.Message) Calendar(java.util.Calendar) Patient(org.openmrs.Patient) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Example 94 with Patient

use of org.openmrs.Patient in project openmrs-core by openmrs.

the class ORUR01HandlerTest method processMessage_shouldCreateAnEncounterAndFindTheProviderByPersonId.

/**
 * @see ORUR01Handler#processMessage(Message)
 */
@Test
public void processMessage_shouldCreateAnEncounterAndFindTheProviderByPersonId() throws Exception {
    int patientId = 2;
    Patient patient = new Patient(patientId);
    List<Encounter> encForPatient1 = Context.getEncounterService().getEncountersByPatient(patient);
    String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||" + patientId + "^^^^||Hornblower^Horatio^Test||\r" + "PV1||O|1^Unknown Location||||1^name|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT";
    Message hl7message = parser.parse(hl7string);
    router.processMessage(hl7message);
    List<Encounter> encForPatient2 = Context.getEncounterService().getEncountersByPatient(patient);
    assertTrue("An encounter should have been created", (encForPatient1.size() + 1) == encForPatient2.size());
    encForPatient2.removeAll(encForPatient1);
    Assert.assertTrue(encForPatient2.size() == 1);
    Provider newProvider = encForPatient2.get(0).getProvidersByRole(Context.getEncounterService().getEncounterRoleByUuid(EncounterRole.UNKNOWN_ENCOUNTER_ROLE_UUID)).iterator().next();
    Assert.assertEquals("c2299800-cca9-11e0-9572-0800200c9a66", newProvider.getUuid());
}
Also used : Message(ca.uhn.hl7v2.model.Message) Patient(org.openmrs.Patient) Encounter(org.openmrs.Encounter) Provider(org.openmrs.Provider) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Example 95 with Patient

use of org.openmrs.Patient in project openmrs-core by openmrs.

the class ORUR01HandlerTest method processMessage_shouldCreateAnEncounterAndFindTheProviderByProviderId.

/**
 * @see ORUR01Handler#processMessage(Message)
 */
@Test
public void processMessage_shouldCreateAnEncounterAndFindTheProviderByProviderId() throws Exception {
    executeDataSet("org/openmrs/api/include/ProviderServiceTest-initial.xml");
    int patientId = 2;
    Patient patient = new Patient(patientId);
    List<Encounter> encForPatient1 = Context.getEncounterService().getEncountersByPatient(patient);
    String hl7string = "MSH|^~\\&|FORMENTRY|AMRS.ELD|HL7LISTENER|AMRS.ELD|20080226102656||ORU^R01|JqnfhKKtouEz8kzTk6Zo|P|2.5|1||||||||16^AMRS.ELD.FORMID\r" + "PID|||" + patientId + "^^^^||Hornblower^Horatio^Test||\r" + "PV1||O|1^Unknown Location||||8^name^^^^^^^&" + HL7Constants.PROVIDER_ASSIGNING_AUTH_PROV_ID + "&L|||||||||||||||||||||||||||||||||||||20080212|||||||V\r" + "ORC|RE||||||||20080226102537|1^Super User\r" + "OBR|1|||1238^MEDICAL RECORD OBSERVATIONS^99DCT";
    Message hl7message = parser.parse(hl7string);
    router.processMessage(hl7message);
    // check for the new encounter
    List<Encounter> encForPatient2 = Context.getEncounterService().getEncountersByPatient(patient);
    encForPatient2.removeAll(encForPatient1);
    Assert.assertTrue(encForPatient2.size() == 1);
    Provider newProvider = encForPatient2.get(0).getProvidersByRole(Context.getEncounterService().getEncounterRoleByUuid(EncounterRole.UNKNOWN_ENCOUNTER_ROLE_UUID)).iterator().next();
    Assert.assertEquals("1f9e8336-6b95-11e0-93c3-18a905e044dc", newProvider.getUuid());
}
Also used : Message(ca.uhn.hl7v2.model.Message) Patient(org.openmrs.Patient) Encounter(org.openmrs.Encounter) Provider(org.openmrs.Provider) Test(org.junit.Test) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest)

Aggregations

Patient (org.openmrs.Patient)389 Test (org.junit.Test)345 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)284 Date (java.util.Date)106 PatientServiceImplTest (org.openmrs.api.impl.PatientServiceImplTest)91 Encounter (org.openmrs.Encounter)76 PatientIdentifier (org.openmrs.PatientIdentifier)60 Location (org.openmrs.Location)57 OrderUtilTest (org.openmrs.order.OrderUtilTest)47 PersonName (org.openmrs.PersonName)43 DrugOrder (org.openmrs.DrugOrder)42 BindException (org.springframework.validation.BindException)38 Concept (org.openmrs.Concept)37 Order (org.openmrs.Order)36 PatientIdentifierType (org.openmrs.PatientIdentifierType)33 Errors (org.springframework.validation.Errors)33 Visit (org.openmrs.Visit)29 ArrayList (java.util.ArrayList)28 Obs (org.openmrs.Obs)28 TestOrder (org.openmrs.TestOrder)28