diff --git a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParameters.java b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParameters.java index 496dc54c4c..815bce20c5 100644 --- a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParameters.java +++ b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParameters.java @@ -3,12 +3,18 @@ import org.apache.commons.lang.StringUtils; import org.openmrs.module.webservices.rest.web.RequestContext; +import java.sql.Timestamp; +import java.util.Date; import java.util.Map; public class PatientSearchParameters { + private final String MIDNIGHT = "00:00:00"; + private Boolean filterPatientsByLocation; private String identifier; private String name; + private String gender; + private Date birthdate; private String addressFieldName; private String addressFieldValue; private Integer start; @@ -43,6 +49,8 @@ public PatientSearchParameters(RequestContext context) { } else { this.setAddressFieldName("city_village"); } + this.setGender(context.getParameter("gender")); + this.setBirthdate(context.getParameter("birthdate")); this.setAddressFieldValue(context.getParameter("addressFieldValue")); Map parameterMap = context.getRequest().getParameterMap(); this.setAddressSearchResultFields((String[]) parameterMap.get("addressSearchResultsConfig")); @@ -71,6 +79,26 @@ public void setName(String name) { this.name = name; } + public String getGender() { + return gender; + } + + public void setGender(String gender) { + this.gender = gender; + } + + public void setBirthdate(String birthdate) { + if(StringUtils.isEmpty(birthdate)) { + return; + } + + this.birthdate = Timestamp.valueOf(setToMidnight(birthdate)); + } + + public Date getBirthdate() { + return birthdate; + } + public String getAddressFieldName() { return addressFieldName; } @@ -174,4 +202,12 @@ public void setFilterOnAllIdentifiers(Boolean filterOnAllIdentifiers) { public Boolean getFilterOnAllIdentifiers() { return filterOnAllIdentifiers; } + + private String setToMidnight(String birthdate) { + if(StringUtils.isNotEmpty(birthdate) && birthdate.matches("\\d{4}-\\d{2}-\\d{2}")) { + return birthdate + " " + MIDNIGHT; + } else { + return birthdate; + } + } } diff --git a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/mapper/PatientResponseMapper.java b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/mapper/PatientResponseMapper.java index 33685f3af3..70b2873a41 100644 --- a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/mapper/PatientResponseMapper.java +++ b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/contract/patient/mapper/PatientResponseMapper.java @@ -1,6 +1,5 @@ package org.bahmni.module.bahmnicore.contract.patient.mapper; -import java.util.Objects; import org.apache.commons.beanutils.PropertyUtils; import org.apache.commons.lang3.StringUtils; import org.bahmni.module.bahmnicore.contract.patient.response.PatientResponse; @@ -21,11 +20,13 @@ import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; +import java.util.Objects; import java.util.Set; import java.util.stream.Collectors; +import static java.util.Arrays.asList; + public class PatientResponseMapper { private PatientResponse patientResponse; private VisitService visitService; @@ -38,8 +39,8 @@ public PatientResponseMapper(VisitService visitService, BahmniVisitLocationServi } public PatientResponse map(Patient patient, String loginLocationUuid, String[] searchResultFields, String[] addressResultFields, Object programAttributeValue) { - List patientSearchResultFields = searchResultFields != null ? Arrays.asList(searchResultFields) : new ArrayList<>(); - List addressSearchResultFields = addressResultFields != null ? Arrays.asList(addressResultFields) : new ArrayList<>(); + List patientSearchResultFields = searchResultFields != null ? asList(searchResultFields) : new ArrayList<>(); + List addressSearchResultFields = addressResultFields != null ? asList(addressResultFields) : new ArrayList<>(); Integer visitLocationId = bahmniVisitLocationService.getVisitLocation(loginLocationUuid).getLocationId(); List activeVisitsByPatient = visitService.getActiveVisitsByPatient(patient); @@ -55,7 +56,9 @@ public PatientResponse map(Patient patient, String loginLocationUuid, String[] s patientResponse.setFamilyName(patient.getFamilyName()); patientResponse.setGender(patient.getGender()); PatientIdentifier primaryIdentifier = patient.getPatientIdentifier(); - patientResponse.setIdentifier(primaryIdentifier.getIdentifier()); + if(primaryIdentifier != null) { + patientResponse.setIdentifier(primaryIdentifier.getIdentifier()); + } patientResponse.setPatientProgramAttributeValue(programAttributeValue); mapExtraIdentifiers(patient, primaryIdentifier); diff --git a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/PatientDao.java b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/PatientDao.java index 0516349ff7..3ee778176c 100644 --- a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/PatientDao.java +++ b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/PatientDao.java @@ -4,6 +4,7 @@ import org.openmrs.Patient; import org.openmrs.RelationshipType; +import java.util.Date; import java.util.List; public interface PatientDao { @@ -19,6 +20,8 @@ List getPatientsUsingLuceneSearch(String identifier, String nam String programAttributeFieldName, String[] addressSearchResultFields, String[] patientSearchResultFields, String loginLocationUuid, Boolean filterPatientsByLocation, Boolean filterOnAllIdentifiers); + List getSimilarPatientsUsingLuceneSearch(String name, String gender, Date birthdate, String loginLocationUuid, Integer length); + public Patient getPatient(String identifier); public List getPatients(String partialIdentifier, boolean shouldMatchExactPatientId); diff --git a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/impl/PatientDaoImpl.java b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/impl/PatientDaoImpl.java index f147768b4c..c315780d7b 100644 --- a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/impl/PatientDaoImpl.java +++ b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/dao/impl/PatientDaoImpl.java @@ -22,20 +22,26 @@ import org.openmrs.Patient; import org.openmrs.PatientIdentifier; import org.openmrs.PatientIdentifierType; +import org.openmrs.Person; +import org.openmrs.PersonName; import org.openmrs.RelationshipType; import org.openmrs.api.context.Context; +import org.openmrs.api.db.hibernate.HibernatePatientDAO; +import org.openmrs.api.db.hibernate.PersonLuceneQuery; +import org.openmrs.api.db.hibernate.search.LuceneQuery; import org.openmrs.module.bahmniemrapi.visitlocation.BahmniVisitLocationServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; + import java.util.ArrayList; -import java.util.Arrays; +import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; -import static java.util.stream.Collectors.reducing; +import static java.util.Arrays.asList; import static java.util.stream.Collectors.toList; @Repository @@ -88,18 +94,74 @@ public List getPatientsUsingLuceneSearch(String identifier, Str List patientResponses = patientIdentifiers.stream() .map(patientIdentifier -> { Patient patient = patientIdentifier.getPatient(); - if(!uniquePatientIds.contains(patient.getPatientId())) { - PatientResponse patientResponse = patientResponseMapper.map(patient, loginLocationUuid, patientSearchResultFields, addressSearchResultFields, - programAttributes.get(patient.getPatientId())); - uniquePatientIds.add(patient.getPatientId()); - return patientResponse; - }else - return null; + return toPatientResponse(patientResponseMapper, patient, loginLocationUuid, addressSearchResultFields, patientSearchResultFields, programAttributes, uniquePatientIds); }).filter(Objects::nonNull) .collect(toList()); return patientResponses; } + @Override + public List getSimilarPatientsUsingLuceneSearch(String name, String gender, Date birthdate, String loginLocationUuid, Integer length) { + PatientResponseMapper patientResponseMapper = new PatientResponseMapper(Context.getVisitService(),new BahmniVisitLocationServiceImpl(Context.getLocationService())); + List patients = getPatientsByNameGenderAndBirthdate(name, gender, birthdate, length); + List patientResponses = patients.stream() + .map(patient -> {return patientResponseMapper.map(patient, loginLocationUuid, null, null,null);}).filter(Objects::nonNull) + .collect(toList()); + return patientResponses; + } + + private PatientResponse toPatientResponse(PatientResponseMapper patientResponseMapper, Patient patient, String loginLocationUuid, String[] addressSearchResultFields, String[] patientSearchResultFields, Map programAttributes, Set uniquePatientIds) { + if(!uniquePatientIds.contains(patient.getPatientId())) { + PatientResponse patientResponse = patientResponseMapper.map(patient, loginLocationUuid, patientSearchResultFields, addressSearchResultFields, + programAttributes.get(patient.getPatientId())); + uniquePatientIds.add(patient.getPatientId()); + return patientResponse; + } else { + return null; + } + } + + private List getPatientsByNameGenderAndBirthdate(String name, String gender, Date birthdate, Integer length) { + if(isAllNullOrEmpty(name, gender, birthdate)) { + return new ArrayList<>(); + } + + HibernatePatientDAO patientDAO = new HibernatePatientDAO(); + patientDAO.setSessionFactory(sessionFactory); + String query = LuceneQuery.escapeQuery(name); + PersonLuceneQuery personLuceneQuery = new PersonLuceneQuery(sessionFactory); + LuceneQuery nameQuery = personLuceneQuery.getPatientNameQuery(query, false); + List patients = nameQuery.list().stream() + .filter(patient -> patient.getPreferred() && checkGender(patient.getPerson(), gender) + && checkBirthdate(patient.getPerson(), birthdate) + ) + .limit(length) + .map(patient -> new Patient(patient.getPerson())) + .collect(toList()); + return patients; + } + + private Boolean isAllNullOrEmpty(String name, String gender, Date birthdate) { + return (name == null || name.trim().isEmpty()) && (gender == null || gender.isEmpty()) && birthdate == null; + } + + + private Boolean checkGender(Person person, String gender) { + if(gender != null && !gender.isEmpty()){ + return gender.equals(person.getGender()); + } else { + return true; + } + } + + private Boolean checkBirthdate(Person person, Date birthdate) { + if(birthdate != null) { + return birthdate.equals(person.getBirthdate()); + } else { + return true; + } + } + private List getPatientIdentifiers(String identifier, Boolean filterOnAllIdentifiers, Integer offset, Integer length) { FullTextSession fullTextSession = Search.getFullTextSession(sessionFactory.getCurrentSession()); QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(PatientIdentifier.class).get(); @@ -108,7 +170,7 @@ private List getPatientIdentifiers(String identifier, Boolean .wildcard().onField("identifierAnywhere").matching("*" + identifier.toLowerCase() + "*").createQuery(); org.apache.lucene.search.Query nonVoidedIdentifiers = queryBuilder.keyword().onField("voided").matching(false).createQuery(); org.apache.lucene.search.Query nonVoidedPatients = queryBuilder.keyword().onField("patient.voided").matching(false).createQuery(); - + List identifierTypeNames = getIdentifierTypeNames(filterOnAllIdentifiers); BooleanJunction identifierTypeShouldJunction = queryBuilder.bool(); @@ -132,7 +194,7 @@ private List getPatientIdentifiers(String identifier, Boolean fullTextQuery.setMaxResults(length); return (List) fullTextQuery.list(); } - + private List getIdentifierTypeNames(Boolean filterOnAllIdentifiers) { List identifierTypeNames = new ArrayList<>(); addIdentifierTypeName(identifierTypeNames,"bahmni.primaryIdentifierType"); @@ -179,7 +241,7 @@ private boolean isValidAddressField(String addressFieldName) { "LOWER (TABLE_NAME) ='person_address' and LOWER(COLUMN_NAME) IN " + "( :personAddressField)"; Query queryToGetAddressFields = sessionFactory.getCurrentSession().createSQLQuery(query); - queryToGetAddressFields.setParameterList("personAddressField", Arrays.asList(addressFieldName.toLowerCase())); + queryToGetAddressFields.setParameterList("personAddressField", asList(addressFieldName.toLowerCase())); List list = queryToGetAddressFields.list(); return list.size() > 0; } @@ -201,7 +263,7 @@ private List getPersonAttributeIds(String[] patientAttributes) { String query = "select person_attribute_type_id from person_attribute_type where name in " + "( :personAttributeTypeNames)"; Query queryToGetAttributeIds = sessionFactory.getCurrentSession().createSQLQuery(query); - queryToGetAttributeIds.setParameterList("personAttributeTypeNames", Arrays.asList(patientAttributes)); + queryToGetAttributeIds.setParameterList("personAttributeTypeNames", asList(patientAttributes)); List list = queryToGetAttributeIds.list(); return (List) list; } @@ -229,7 +291,7 @@ public List getPatients(String patientIdentifier, boolean shouldMatchEx } Patient patient = getPatient(patientIdentifier); - List result = (patient == null ? new ArrayList() : Arrays.asList(patient)); + List result = (patient == null ? new ArrayList() : asList(patient)); return result; } diff --git a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/BahmniPatientService.java b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/BahmniPatientService.java index 5a3905ba5f..eb598e582b 100644 --- a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/BahmniPatientService.java +++ b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/BahmniPatientService.java @@ -1,9 +1,11 @@ package org.bahmni.module.bahmnicore.service; import org.bahmni.module.bahmnicore.contract.patient.PatientSearchParameters; +import org.bahmni.module.bahmnicore.contract.patient.mapper.PatientResponseMapper; import org.bahmni.module.bahmnicore.contract.patient.response.PatientConfigResponse; import org.bahmni.module.bahmnicore.contract.patient.response.PatientResponse; import org.openmrs.Patient; +import org.openmrs.Person; import org.openmrs.RelationshipType; import java.util.List; @@ -15,6 +17,8 @@ public interface BahmniPatientService { List luceneSearch(PatientSearchParameters searchParameters); + List searchSimilarPatients(PatientSearchParameters searchParameters); + public List get(String partialIdentifier, boolean shouldMatchExactPatientId); public List getByAIsToB(String aIsToB); diff --git a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImpl.java b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImpl.java index 0c50fae0a8..fb06fb4ed5 100644 --- a/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImpl.java +++ b/bahmnicore-api/src/main/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImpl.java @@ -20,6 +20,7 @@ @Service @Lazy //to get rid of cyclic dependencies public class BahmniPatientServiceImpl implements BahmniPatientService { + private static final int SIMILAR_PATIENT_RESULT_LENGTH = 5; private PersonService personService; private ConceptService conceptService; private PatientDao patientDao; @@ -83,6 +84,15 @@ public List luceneSearch(PatientSearchParameters searchParamete searchParameters.getFilterPatientsByLocation(), searchParameters.getFilterOnAllIdentifiers()); } + @Override + public List searchSimilarPatients(PatientSearchParameters searchParameters) { + return patientDao.getSimilarPatientsUsingLuceneSearch(searchParameters.getName(), + searchParameters.getGender(), + searchParameters.getBirthdate(), + searchParameters.getLoginLocationUuid(), + SIMILAR_PATIENT_RESULT_LENGTH); + } + @Override public List get(String partialIdentifier, boolean shouldMatchExactPatientId) { return patientDao.getPatients(partialIdentifier, shouldMatchExactPatientId); diff --git a/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParametersTest.java b/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParametersTest.java new file mode 100644 index 0000000000..e51848f193 --- /dev/null +++ b/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/contract/patient/PatientSearchParametersTest.java @@ -0,0 +1,46 @@ +package org.bahmni.module.bahmnicore.contract.patient; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mock; +import org.openmrs.module.webservices.rest.web.RequestContext; + +import javax.servlet.http.HttpServletRequest; +import java.sql.Timestamp; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.when; +import static org.mockito.MockitoAnnotations.initMocks; + + +public class PatientSearchParametersTest { + + @Mock + RequestContext requestContext; + + @Mock + HttpServletRequest request; + + @Before + public void setup() { + initMocks(this); + when(requestContext.getRequest()).thenReturn(request); + } + + @Test + public void shouldIgnoreEmptyBirthdate () { + when(requestContext.getParameter("birthdate")).thenReturn(""); + PatientSearchParameters patientSearchParameters = new PatientSearchParameters(requestContext); + + assertNull(patientSearchParameters.getBirthdate()); + } + + @Test + public void shouldParseBirthdateFromStringAndSetToMidnight () { + when(requestContext.getParameter("birthdate")).thenReturn("1983-01-30"); + PatientSearchParameters patientSearchParameters = new PatientSearchParameters(requestContext); + + assertEquals(Timestamp.valueOf("1983-01-30 00:00:00"), patientSearchParameters.getBirthdate()); + } +} \ No newline at end of file diff --git a/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/dao/impl/BahmniPatientDaoImplLuceneIT.java b/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/dao/impl/BahmniPatientDaoImplLuceneIT.java index c02cfc7bc0..bc949f5e1e 100644 --- a/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/dao/impl/BahmniPatientDaoImplLuceneIT.java +++ b/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/dao/impl/BahmniPatientDaoImplLuceneIT.java @@ -7,10 +7,12 @@ import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.openmrs.Patient; import org.springframework.beans.factory.annotation.Autowired; +import java.sql.Timestamp; +import java.util.Date; import java.util.List; + import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertNull; @@ -21,13 +23,13 @@ public class BahmniPatientDaoImplLuceneIT extends BaseIntegrationTest { private PatientDao patientDao; @Rule public ExpectedException expectedEx = ExpectedException.none(); - + @Before public void setUp() throws Exception { executeDataSet("apiTestData.xml"); updateSearchIndex(); } - + @Test public void shouldSearchByPatientPrimaryIdentifier() { String[] addressResultFields = {"city_village"}; @@ -45,7 +47,7 @@ public void shouldSearchByPatientPrimaryIdentifier() { assertEquals(null, patient.getDeathDate()); assertEquals("{\"National ID\" : \"NAT100010\"}", patient.getExtraIdentifiers()); } - + @Test public void shouldSearchByPatientExtraIdentifier() { String[] addressResultFields = {"city_village"}; @@ -63,35 +65,35 @@ public void shouldSearchByPatientExtraIdentifier() { assertEquals(null, patient.getDeathDate()); assertEquals("{\"National ID\" : \"NAT100010\"}", patient.getExtraIdentifiers()); } - + @Test public void shouldSearchByPartialPatientIdentifier() { List patients = patientDao.getPatientsUsingLuceneSearch("02", "", null, "city_village", "", 100, 0, null,"",null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); assertEquals(1, patients.size()); PatientResponse patient = patients.get(0); - + assertEquals("GAN200002", patient.getIdentifier()); assertNull(patient.getExtraIdentifiers()); } - + @Test public void shouldReturnResultAfterGivenOffset() throws Exception { List patients = patientDao.getPatientsUsingLuceneSearch("300001", "", null, "city_village", "", 100, 1, null,"",null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); assertEquals(1, patients.size()); - + patients = patientDao.getPatientsUsingLuceneSearch("300001", "", null, "city_village", "", 100, 2, null,"",null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); assertEquals(0, patients.size()); } - + @Test public void shouldThrowErrorWhenPatientAttributesIsNotPresent() throws Exception { String[] patientAttributes = {"caste","nonExistingAttribute"}; expectedEx.expect(IllegalArgumentException.class); expectedEx.expectMessage("Invalid Attribute In Patient Attributes [caste, nonExistingAttribute]"); List patients = patientDao.getPatientsUsingLuceneSearch("", "", "testCaste1", "city_village", null, 100, 0, patientAttributes, "", null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + } - + @Test public void shouldThrowErrorWhenPatientAddressIsNotPresent() throws Exception { String[] patientAttributes = {"caste"}; @@ -99,31 +101,31 @@ public void shouldThrowErrorWhenPatientAddressIsNotPresent() throws Exception { expectedEx.expect(IllegalArgumentException.class); expectedEx.expectMessage("Invalid Address Filed nonExistingAddressFiled"); List patients = patientDao.getPatientsUsingLuceneSearch("", "", "testCaste1", addressField, null, 100, 0, patientAttributes, "", null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + } - + @Test public void shouldThrowErrorWhenProgramAttributesIsNotPresent() { String nonExistingAttribute = "nonExistingAttribute"; expectedEx.expect(IllegalArgumentException.class); expectedEx.expectMessage("Invalid Program Attribute nonExistingAttribute"); patientDao.getPatientsUsingLuceneSearch("", "", "", "city_village", null, 100, 0, null, "Stage1",nonExistingAttribute, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + } - + @Test public void shouldReturnAdmissionStatus() throws Exception{ List patients = patientDao.getPatientsUsingLuceneSearch("200000", null, null, "city_village", null, 10, 0, null, null, null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); assertEquals(1, patients.size()); PatientResponse patient200000 = patients.get(0); assertFalse(patient200000.getHasBeenAdmitted()); - + patients = patientDao.getPatientsUsingLuceneSearch("200002", null, null, "city_village", null, 10, 0, null, null, null,null,null, "8d6c993e-c2cc-11de-8d13-0040c6dffd0f", false, false); assertEquals(1, patients.size()); PatientResponse patient200003 = patients.get(0); assertTrue(patient200003.getHasBeenAdmitted()); } - + @Test public void shouldReturnAddressAndPatientAttributes() throws Exception{ String[] addressResultFields = {"address3"}; @@ -134,83 +136,158 @@ public void shouldReturnAddressAndPatientAttributes() throws Exception{ assertTrue("{\"middleNameLocal\" : \"singh\",\"familyNameLocal\" : \"gond\",\"givenNameLocal\" : \"ram\"}".equals(patient200002.getCustomAttribute())); assertTrue("{\"address3\" : \"Dindori\"}".equals(patient200002.getAddressFieldValue())); } - + @Test public void shouldGiveAllThePatientsIfWeSearchWithPercentileAsIdentifier() throws Exception { List patients = patientDao.getPatientsUsingLuceneSearch("%", null, null, null, null, 10, 0, null, null, null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + assertEquals(10, patients.size()); } - + @Test public void shouldFetchPatientsByPatientIdentifierWhenThereIsSingleQuoteInPatientIdentifier(){ List patients = patientDao.getPatientsUsingLuceneSearch("51'0003", "", "", null, null, 100, 0, null,null, null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + PatientResponse response = patients.get(0); - + assertEquals(1, patients.size()); assertEquals("SEV51'0003", response.getIdentifier()); } - + @Test public void shouldFetchPatientsByPatientIdentifierWhenThereIsJustOneSingleQuoteInPatientIdentifier() throws Exception { List patients = patientDao.getPatientsUsingLuceneSearch("'", "", "", null, null, 100, 0, null,null, null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + PatientResponse response = patients.get(0); - + assertEquals(1, patients.size()); assertEquals("SEV51'0003", response.getIdentifier()); } - + @Test public void shouldSearchPatientsByPatientIdentifierWhenThereAreMultipleSinglesInSearchString() throws Exception { - + List patients = patientDao.getPatientsUsingLuceneSearch("'''", "", "", null, null, 100, 0, null,null, null,null,null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + assertEquals(0, patients.size()); } - + @Test public void shouldNotReturnDuplicatePatientsEvenIfThereAreMultipleVisitsForThePatients() { List patients = patientDao.getPatientsUsingLuceneSearch("HOS1225", "", null, "city_village", "", 100, 0, null,"",null,null,null, "8d6c993e-c2cc-11de-8d34-0010c6affd0f", false, false); - + assertEquals(1, patients.size()); PatientResponse patient1 = patients.get(0); - + assertEquals("1058GivenName", patient1.getGivenName()); } - + @Test public void shouldNotSearchExtraIdentifiersIfFilterOnAllIdenfiersIsFalse() { List patients = patientDao.getPatientsUsingLuceneSearch("100010", "", null, "city_village", "", 100, 0, null,"", null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, false); - + assertEquals(0, patients.size()); } - + @Test public void shouldSearchAllIdentifiersIfFilterOnAllIdentifiersIsTrue() { List patients = patientDao.getPatientsUsingLuceneSearch("0001", "", null, "city_village", "", 100, 0, null,"", null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, true); - + assertEquals(3, patients.size()); assertEquals("{\"National ID\" : \"NAT100010\"}", patients.get(0).getExtraIdentifiers()); assertEquals("GAN300001",patients.get(1).getIdentifier()); } - + @Test public void shouldNotReturnPatientsIfFilterOnAllIdenfiersIsTrueButNotAnExtraIdentifier() { List patients = patientDao.getPatientsUsingLuceneSearch("DLF200001", "", null, "city_village", "", 100, 0, null,"", null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, true); - + assertEquals(0, patients.size()); } - + @Test public void shouldNotReturnDuplicatePatientsEvenIfTwoIdentifiersMatches() { List patients = patientDao.getPatientsUsingLuceneSearch("200006", "", null, "city_village", "", 100, 0, null,"", null, null, null, "c36006e5-9fbb-4f20-866b-0ece245615a1", false, true); - + assertEquals(1, patients.size()); PatientResponse patient = patients.get(0); assertTrue(patient.getIdentifier().contains("200006")); assertTrue(patient.getExtraIdentifiers().contains("200006")); } + @Test + public void shouldSearchSimilarPatientByPatientName() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("Peet", "", null, "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + assertEquals(2, patients.size()); + + PatientResponse patient1 = patients.get(0); + PatientResponse patient2 = patients.get(1); + assertEquals(patient1.getGivenName(), "Horatio"); + assertEquals(patient1.getMiddleName(), "Peeter"); + assertEquals(patient1.getFamilyName(), "Sinha"); + assertEquals(patient2.getGivenName(), "John"); + assertEquals(patient2.getMiddleName(), "Peeter"); + assertEquals(patient2.getFamilyName(), "Sinha"); + } + + @Test + public void shouldSearchSimilarPatientByPatientNameAndUseLimitResult() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("Peet", "", null, "c36006e5-9fbb-4f20-866b-0ece245615a1", 1); + assertEquals("Should limit number of results",1, patients.size()); + PatientResponse patient1 = patients.get(0); + + assertEquals(patient1.getGivenName(), "Horatio"); + assertEquals(patient1.getMiddleName(), "Peeter"); + assertEquals(patient1.getFamilyName(), "Sinha"); + } + + @Test + public void shouldSearchSimilarPatientByPatientNameAndGender() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("Peet", "F", null, "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + + assertEquals(1, patients.size()); + PatientResponse patient1 = patients.get(0); + assertEquals(patient1.getGivenName(), "John"); + assertEquals(patient1.getMiddleName(), "Peeter"); + assertEquals(patient1.getFamilyName(), "Sinha"); + } + + @Test + public void shouldSearchSimilarPatientByNameAndBirthdate() { + Date birthdate = Timestamp.valueOf("1983-01-30 00:00:00"); + + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("Sinha", "", birthdate, "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + + assertEquals(1, patients.size()); + PatientResponse patient = patients.get(0); + assertEquals(patient.getBirthDate(), birthdate); + } + + @Test + public void shouldMatchAllNamesInSearchSimilarPatient() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("Horatio Peet", "", null, "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + + assertEquals("Should use an AND query on names",1, patients.size()); + } + + @Test + public void shouldReturnEmptyListIfAllSearchTermsAreEmpty() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("", "", null, "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + + assertEquals(0, patients.size()); + } + + @Test + public void shouldReturnResultsIfOnlyGenderIsSet() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("", "F", null, "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + + assertEquals(5, patients.size()); + } + + @Test + public void shouldReturnResultsIfOnlyBirthdateIsSet() { + List patients = patientDao.getSimilarPatientsUsingLuceneSearch("", "", Timestamp.valueOf("1983-01-30 00:00:00"), "c36006e5-9fbb-4f20-866b-0ece245615a1", 5); + + assertEquals(1, patients.size()); + } } diff --git a/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImplTest.java b/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImplTest.java index 5c77844fdb..1d86feb7df 100644 --- a/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImplTest.java +++ b/bahmnicore-api/src/test/java/org/bahmni/module/bahmnicore/service/impl/BahmniPatientServiceImplTest.java @@ -1,5 +1,6 @@ package org.bahmni.module.bahmnicore.service.impl; +import org.bahmni.module.bahmnicore.contract.patient.PatientSearchParameters; import org.bahmni.module.bahmnicore.contract.patient.response.PatientConfigResponse; import org.bahmni.module.bahmnicore.dao.PatientDao; import org.junit.Before; @@ -9,12 +10,17 @@ import org.openmrs.PersonAttributeType; import org.openmrs.api.ConceptService; import org.openmrs.api.PersonService; +import org.openmrs.module.webservices.rest.web.RequestContext; +import javax.servlet.http.HttpServletRequest; +import java.sql.Timestamp; import java.util.ArrayList; +import java.util.HashMap; import java.util.List; import static junit.framework.Assert.assertEquals; -import static org.mockito.Mockito.anyInt; +import static org.mockito.Matchers.anyInt; +import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.initMocks; @@ -25,6 +31,8 @@ public class BahmniPatientServiceImplTest { @Mock private ConceptService conceptService; @Mock + RequestContext requestContext; + @Mock private PatientDao patientDao; private BahmniPatientServiceImpl bahmniPatientService; @@ -67,4 +75,19 @@ public void shouldGetPatientByPartialIdentifier() throws Exception { bahmniPatientService.get("partial_identifier", shouldMatchExactPatientId); verify(patientDao).getPatients("partial_identifier", shouldMatchExactPatientId); } + + @Test + public void shouldCallGetSimilarPatientsUsingLuceneSearch() { + HttpServletRequest request = mock(HttpServletRequest.class); + when(requestContext.getRequest()).thenReturn(request); + when(request.getParameterMap()).thenReturn(new HashMap<>()); + PatientSearchParameters patientSearchParameters = new PatientSearchParameters(requestContext); + patientSearchParameters.setName("John"); + patientSearchParameters.setGender("M"); + patientSearchParameters.setBirthdate("1983-01-30 00:00:00"); + patientSearchParameters.setLoginLocationUuid("someUUid"); + + bahmniPatientService.searchSimilarPatients(patientSearchParameters); + verify(patientDao).getSimilarPatientsUsingLuceneSearch("John", "M", Timestamp.valueOf("1983-01-30 00:00:00"), "someUUid", 5); + } } diff --git a/bahmnicore-omod/src/main/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchController.java b/bahmnicore-omod/src/main/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchController.java index a3d71c703a..9885526517 100644 --- a/bahmnicore-omod/src/main/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchController.java +++ b/bahmnicore-omod/src/main/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchController.java @@ -66,4 +66,19 @@ public ResponseEntity> luceneSearch(HttpServletReq return new ResponseEntity(RestUtil.wrapErrorResponse(e, e.getMessage()), HttpStatus.BAD_REQUEST); } } + + @RequestMapping(value="similar", method = RequestMethod.GET) + @ResponseBody + public ResponseEntity> searchSimilarPerson(HttpServletRequest request, + HttpServletResponse response) throws ResponseException{ + RequestContext requestContext = RestUtil.getRequestContext(request, response); + PatientSearchParameters searchParameters = new PatientSearchParameters(requestContext); + try { + List patients = bahmniPatientService.searchSimilarPatients(searchParameters); + AlreadyPaged alreadyPaged = new AlreadyPaged(requestContext, patients, false); + return new ResponseEntity(alreadyPaged, HttpStatus.OK); + }catch (IllegalArgumentException e){ + return new ResponseEntity(RestUtil.wrapErrorResponse(e, e.getMessage()), HttpStatus.BAD_REQUEST); + } + } } diff --git a/bahmnicore-omod/src/test/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchControllerIT.java b/bahmnicore-omod/src/test/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchControllerIT.java new file mode 100644 index 0000000000..49b934883e --- /dev/null +++ b/bahmnicore-omod/src/test/java/org/bahmni/module/bahmnicore/web/v1_0/controller/search/BahmniPatientSearchControllerIT.java @@ -0,0 +1,46 @@ +package org.bahmni.module.bahmnicore.web.v1_0.controller.search; + +import org.bahmni.module.bahmnicore.web.v1_0.BaseIntegrationTest; +import org.junit.Before; +import org.junit.Test; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +public class BahmniPatientSearchControllerIT extends BaseIntegrationTest { + + @Before + public void setup() throws Exception { + executeDataSet("apiTestData.xml"); + updateSearchIndex(); + } + + @Test + public void shouldReturnPatientDetailsWhenUsingLuceneSearch() throws Exception { + MockHttpServletRequest request = newGetRequest("/rest/v1/bahmnicore/search/patient/lucene"); + request.setParameter("loginLocationUuid", "c36006e5-9fbb-4f20-866b-0ece245615a1"); + request.setParameter("q", "GAN200001"); + + MockHttpServletResponse response = handle(request); + + assertEquals(200, response.getStatus()); + assertTrue("Expected response to contain patient uuid", response.getContentAsString().contains("uuid")); + } + + @Test + public void shouldReturnPatientDetailsWhenUsingSimilarSearch() throws Exception { + MockHttpServletRequest request = newGetRequest("/rest/v1/bahmnicore/search/patient/similar"); + request.setParameter("gender", "M"); + request.setParameter("birthdate", "1983-01-30 00:00:00"); + request.setParameter("loginLocationUuid", "c36006e5-9fbb-4f20-866b-0ece245615a1"); + request.setParameter("q", "Sinha"); + + MockHttpServletResponse response = handle(request); + + assertEquals(200, response.getStatus()); + assertTrue("Expected response to contain list of results", response.getContentAsString().contains("pageOfResults")); + assertTrue("Expected response to contain patient uuid", response.getContentAsString().contains("uuid")); + } +} \ No newline at end of file