Search in sources :

Example 16 with PatientIdentifierType

use of org.openmrs.PatientIdentifierType 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 17 with PatientIdentifierType

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

the class MigrationHelper method importRelationships.

/**
 * Takes a list of Strings of the format RELATIONSHIP:&lt;user last name&gt;,&lt;user first
 * name&gt;,&lt;relationship type name&gt;,&lt;patient identifier type name&gt;,&lt;identifier&gt; so if user hfraser
 * if the cardiologist of the patient with patient_id 8039 in PIH's old emr, then:
 * RELATIONSHIP:hfraser,Cardiologist,HIV-EMRV1,8039 (the "RELATIONSHIP:" is not actually
 * necessary. Anything before and including the first : will be dropped If autoCreateUsers is
 * true, and no user exists with the given username, one will be created. If autoAddRole is
 * true, then whenever a user is auto-created, if a role exists with the same name as
 * relationshipType.name, then the user will be added to that role
 */
public static int importRelationships(Collection<String> relationships, boolean autoCreateUsers, boolean autoAddRole) {
    PatientService ps = Context.getPatientService();
    UserService us = Context.getUserService();
    PersonService personService = Context.getPersonService();
    List<Relationship> relsToAdd = new ArrayList<>();
    Random rand = new Random();
    for (String s : relationships) {
        if (s.contains(":")) {
            s = s.substring(s.indexOf(":") + 1);
        }
        String[] ss = s.split(",");
        if (ss.length < 5) {
            throw new IllegalArgumentException("The line '" + s + "' is in the wrong format");
        }
        String userLastName = ss[0];
        String userFirstName = ss[1];
        String username = (userFirstName + userLastName).replaceAll(" ", "");
        String relationshipType = ss[2];
        String identifierType = ss[3];
        String identifier = ss[4];
        User user = null;
        {
            // first try looking for non-voided users
            List<User> users = us.getUsersByName(userFirstName, userLastName, false);
            if (users.size() == 1) {
                user = users.get(0);
            } else if (users.size() > 1) {
                throw new IllegalArgumentException("Found " + users.size() + " users named '" + userLastName + ", " + userFirstName + "'");
            }
        }
        if (user == null) {
            // next try looking for voided users
            List<User> users = us.getUsersByName(userFirstName, userLastName, false);
            if (users.size() == 1) {
                user = users.get(0);
            } else if (users.size() > 1) {
                throw new IllegalArgumentException("Found " + users.size() + " voided users named '" + userLastName + ", " + userFirstName + "'");
            }
        }
        if (user == null && autoCreateUsers) {
            user = new User();
            user.setPerson(new Person());
            PersonName pn = new PersonName(userFirstName, "", userLastName);
            user.addName(pn);
            user.setUsername(username);
            // Generate a temporary password: 8-12 random characters
            String pass;
            {
                int length = rand.nextInt(4) + 8;
                char[] password = new char[length];
                for (int x = 0; x < length; x++) {
                    int randDecimalAsciiVal = rand.nextInt(93) + 33;
                    password[x] = (char) randDecimalAsciiVal;
                }
                pass = new String(password);
            }
            if (autoAddRole) {
                Role role = us.getRole(relationshipType);
                if (role != null) {
                    user.addRole(role);
                }
            }
            us.createUser(user, pass);
        }
        if (user == null) {
            throw new IllegalArgumentException("Can't find user '" + userLastName + ", " + userFirstName + "'");
        }
        Person person = personService.getPerson(user.getUserId());
        RelationshipType relationship = personService.getRelationshipTypeByName(relationshipType);
        PatientIdentifierType pit = ps.getPatientIdentifierTypeByName(identifierType);
        List<PatientIdentifier> found = ps.getPatientIdentifiers(identifier, Collections.singletonList(pit), null, null, null);
        if (found.size() != 1) {
            throw new IllegalArgumentException("Found " + found.size() + " patients with identifier '" + identifier + "' of type " + identifierType);
        }
        Person relative = personService.getPerson(found.get(0).getPatient().getPatientId());
        Relationship rel = new Relationship();
        rel.setPersonA(person);
        rel.setRelationshipType(relationship);
        rel.setPersonB(relative);
        relsToAdd.add(rel);
    }
    int addedSoFar = 0;
    for (Relationship rel : relsToAdd) {
        personService.saveRelationship(rel);
        ++addedSoFar;
    }
    return addedSoFar;
}
Also used : PersonName(org.openmrs.PersonName) User(org.openmrs.User) UserService(org.openmrs.api.UserService) PersonService(org.openmrs.api.PersonService) ArrayList(java.util.ArrayList) RelationshipType(org.openmrs.RelationshipType) PatientIdentifier(org.openmrs.PatientIdentifier) Role(org.openmrs.Role) Random(java.util.Random) PatientService(org.openmrs.api.PatientService) Relationship(org.openmrs.Relationship) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) Person(org.openmrs.Person) PatientIdentifierType(org.openmrs.PatientIdentifierType)

Example 18 with PatientIdentifierType

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

the class PatientServiceTest method isIdentifierInUseByAnotherPatient_shouldReturnTrueIfInUseForALocationAndIdTypeUniquenessIsSetToLocation.

/**
 * @see PatientService#isIdentifierInUseByAnotherPatient(PatientIdentifier)
 */
@Test
public void isIdentifierInUseByAnotherPatient_shouldReturnTrueIfInUseForALocationAndIdTypeUniquenessIsSetToLocation() throws Exception {
    PatientIdentifier duplicateId = patientService.getPatientIdentifier(1);
    Assert.assertNotNull(duplicateId.getLocation());
    PatientIdentifierType idType = duplicateId.getIdentifierType();
    idType.setUniquenessBehavior(UniquenessBehavior.LOCATION);
    patientService.savePatientIdentifierType(idType);
    PatientIdentifier pi = new PatientIdentifier(duplicateId.getIdentifier(), idType, duplicateId.getLocation());
    Assert.assertTrue(patientService.isIdentifierInUseByAnotherPatient(pi));
}
Also used : PatientIdentifier(org.openmrs.PatientIdentifier) PatientIdentifierType(org.openmrs.PatientIdentifierType) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest) PatientServiceImplTest(org.openmrs.api.impl.PatientServiceImplTest) Test(org.junit.Test)

Example 19 with PatientIdentifierType

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

the class PatientServiceTest method isIdentifierInUseByAnotherPatient_shouldIgnoreVoidedPatientIdentifiers.

/**
 * @see PatientService#isIdentifierInUseByAnotherPatient(PatientIdentifier)
 */
@Test
public void isIdentifierInUseByAnotherPatient_shouldIgnoreVoidedPatientIdentifiers() throws Exception {
    PatientIdentifierType pit = patientService.getPatientIdentifierType(2);
    PatientIdentifier patientIdentifier = new PatientIdentifier("ABC123", pit, null);
    Assert.assertFalse(patientService.isIdentifierInUseByAnotherPatient(patientIdentifier));
}
Also used : PatientIdentifierType(org.openmrs.PatientIdentifierType) PatientIdentifier(org.openmrs.PatientIdentifier) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest) PatientServiceImplTest(org.openmrs.api.impl.PatientServiceImplTest) Test(org.junit.Test)

Example 20 with PatientIdentifierType

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

the class PatientServiceTest method savePatient_shouldCreateNewPatientFromExistingPersonPlusUserObject.

/**
 * @see PatientService#savePatient(Patient)
 */
@Test
public void savePatient_shouldCreateNewPatientFromExistingPersonPlusUserObject() throws Exception {
    // sanity check, make sure there isn't a 501 patient already
    Patient oldPatient = patientService.getPatient(501);
    Assert.assertNull(oldPatient);
    // fetch Bruno from the database
    Person existingPerson = Context.getPersonService().getPerson(501);
    Context.clearSession();
    Patient patient = new Patient(existingPerson);
    PatientIdentifier patientIdentifier = new PatientIdentifier("some identifier", new PatientIdentifierType(2), new Location(1));
    patientIdentifier.setPreferred(true);
    patient.addIdentifier(patientIdentifier);
    patientService.savePatient(patient);
    Assert.assertEquals(501, patient.getPatientId().intValue());
    // make sure a new row with a patient id WAS created
    Assert.assertNotNull(patientService.getPatient(501));
    // make sure a new row with a new person id WASN'T created
    Assert.assertNull(patientService.getPatient(503));
}
Also used : Patient(org.openmrs.Patient) Person(org.openmrs.Person) PatientIdentifier(org.openmrs.PatientIdentifier) PatientIdentifierType(org.openmrs.PatientIdentifierType) Location(org.openmrs.Location) BaseContextSensitiveTest(org.openmrs.test.BaseContextSensitiveTest) PatientServiceImplTest(org.openmrs.api.impl.PatientServiceImplTest) Test(org.junit.Test)

Aggregations

PatientIdentifierType (org.openmrs.PatientIdentifierType)131 Test (org.junit.Test)99 BaseContextSensitiveTest (org.openmrs.test.BaseContextSensitiveTest)88 PatientIdentifier (org.openmrs.PatientIdentifier)56 PatientServiceImplTest (org.openmrs.api.impl.PatientServiceImplTest)53 Patient (org.openmrs.Patient)37 Location (org.openmrs.Location)29 ArrayList (java.util.ArrayList)20 BindException (org.springframework.validation.BindException)17 Errors (org.springframework.validation.Errors)14 Date (java.util.Date)13 PersonName (org.openmrs.PersonName)13 User (org.openmrs.User)7 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)7 Concept (org.openmrs.Concept)6 Person (org.openmrs.Person)5 HashMap (java.util.HashMap)4 PersonAddress (org.openmrs.PersonAddress)4 PatientServiceTest (org.openmrs.api.PatientServiceTest)4 HL7Exception (ca.uhn.hl7v2.HL7Exception)3