Search in sources :

Example 1 with DiagnosisMetadata

use of org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata in project openmrs-module-pihcore by PIH.

the class DiagnosisCohortDefinitionEvaluator method evaluate.

@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException {
    DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();
    DiagnosisCohortDefinition cd = (DiagnosisCohortDefinition) cohortDefinition;
    if (cd.isIncludeAllCodedDiagnoses() && cd.getCodedDiagnoses() != null) {
        throw new IllegalArgumentException("Cannot specify both includeAllCodedDiagnoses, and specific coded diagnoses");
    }
    Criteria crit = sessionFactory.getCurrentSession().createCriteria(Obs.class, "obsgroup");
    crit.setProjection(Projections.distinct(Projections.property("person.id")));
    crit.add(Restrictions.eq("voided", false));
    crit.createCriteria("person").add(Restrictions.eq("voided", false));
    // we're looking for an obs group whose grouping concept is VISIT DIAGNOSES (or the equivalent)
    crit.add(Restrictions.eq("concept", dmd.getDiagnosisSetConcept()));
    if (cd.getOnOrAfter() != null) {
        crit.add(Restrictions.ge("obsDatetime", cd.getOnOrAfter()));
    }
    if (cd.getOnOrBefore() != null) {
        crit.add(Restrictions.le("obsDatetime", DateUtil.getEndOfDayIfTimeExcluded(cd.getOnOrBefore())));
    }
    if (cd.getDiagnosisOrder() != null) {
        DetachedCriteria orderClause = DetachedCriteria.forClass(Obs.class, "orderObs");
        orderClause.add(Restrictions.eq("voided", false));
        orderClause.add(Restrictions.eq("concept", dmd.getDiagnosisOrderConcept()));
        orderClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getDiagnosisOrder())));
        orderClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        orderClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(orderClause));
    }
    if (cd.getCertainty() != null) {
        DetachedCriteria certaintyClause = DetachedCriteria.forClass(Obs.class, "certaintyObs");
        certaintyClause.add(Restrictions.eq("voided", false));
        certaintyClause.add(Restrictions.eq("concept", dmd.getDiagnosisCertaintyConcept()));
        certaintyClause.add(Restrictions.eq("valueCoded", dmd.getConceptFor(cd.getCertainty())));
        certaintyClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        certaintyClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(certaintyClause));
    }
    if (cd.isIncludeAllCodedDiagnoses()) {
        // diagnoses, we can just ignore both clauses
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria anyCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            anyCodedClause.add(Restrictions.eq("voided", false));
            anyCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            anyCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            anyCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(anyCodedClause));
        }
    } else if (cd.getCodedDiagnoses() != null || cd.getExcludeCodedDiagnoses() != null) {
        if (cd.isIncludeAllNonCodedDiagnoses()) {
            throw new IllegalArgumentException("Not Yet Implemented: handling both all-non-coded and specific coded diagnoses together");
        }
        if (!cd.isIncludeAllNonCodedDiagnoses()) {
            DetachedCriteria specificCodedClause = DetachedCriteria.forClass(Obs.class, "codedDiagnosisObs");
            specificCodedClause.add(Restrictions.eq("voided", false));
            specificCodedClause.add(Restrictions.eq("concept", dmd.getCodedDiagnosisConcept()));
            if (cd.getCodedDiagnoses() != null) {
                specificCodedClause.add(Restrictions.in("valueCoded", cd.getCodedDiagnoses()));
            }
            if (cd.getExcludeCodedDiagnoses() != null) {
                specificCodedClause.add(Restrictions.not(Restrictions.in("valueCoded", cd.getExcludeCodedDiagnoses())));
            }
            specificCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
            specificCodedClause.setProjection(Projections.property("id"));
            crit.add(Subqueries.exists(specificCodedClause));
        }
    } else if (cd.isIncludeAllNonCodedDiagnoses()) {
        DetachedCriteria anyNonCodedClause = DetachedCriteria.forClass(Obs.class, "nonCodedDiagnosisObs");
        anyNonCodedClause.add(Restrictions.eq("voided", false));
        anyNonCodedClause.add(Restrictions.eq("concept", dmd.getNonCodedDiagnosisConcept()));
        anyNonCodedClause.add(Restrictions.eqProperty("obsGroup", "obsgroup.id"));
        anyNonCodedClause.setProjection(Projections.property("id"));
        crit.add(Subqueries.exists(anyNonCodedClause));
    }
    Cohort c = new Cohort();
    for (Integer i : (List<Integer>) crit.list()) {
        c.addMember(i);
    }
    return new EvaluatedCohort(c, cohortDefinition, context);
}
Also used : Obs(org.openmrs.Obs) Cohort(org.openmrs.Cohort) EvaluatedCohort(org.openmrs.module.reporting.cohort.EvaluatedCohort) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) EvaluatedCohort(org.openmrs.module.reporting.cohort.EvaluatedCohort) List(java.util.List) Criteria(org.hibernate.Criteria) DetachedCriteria(org.hibernate.criterion.DetachedCriteria) DiagnosisCohortDefinition(org.openmrs.module.pihcore.reporting.cohort.definition.DiagnosisCohortDefinition)

Example 2 with DiagnosisMetadata

use of org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata in project openmrs-module-coreapps by openmrs.

the class EncounterDiagnosesElement method handleSubmission.

@Override
public void handleSubmission(FormEntrySession formEntrySession, HttpServletRequest request) {
    DiagnosisMetadata diagnosisMetadata = emrApiProperties.getDiagnosisMetadata();
    String submitted = request.getParameter("encounterDiagnoses");
    // if we are in edit mode, we need to map the submitted diagnoses to their existing obs
    Map<Integer, Obs> existingDiagnosisObs = getExistingDiagnosisObs(formEntrySession.getContext(), diagnosisMetadata);
    FormSubmissionActions submissionActions = formEntrySession.getSubmissionActions();
    try {
        // we need to void any existing that isn't resubmitted
        Set<Integer> resubmittedObs = new HashSet<Integer>();
        List<Diagnosis> diagnoses = parseDiagnoses(submitted, existingDiagnosisObs);
        for (Diagnosis diagnosis : diagnoses) {
            if (diagnosis.getExistingObs() != null) {
                resubmittedObs.add(diagnosis.getExistingObs().getId());
            }
            Obs obsGroup = diagnosisMetadata.buildDiagnosisObsGroup(diagnosis);
            createObsGroup(submissionActions, obsGroup);
        }
        if (formEntrySession.getContext().getMode().equals(FormEntryContext.Mode.EDIT)) {
            // void any diagnosis that wasn't resubmitted
            Collection<Integer> obsToVoid = CollectionUtils.subtract(existingDiagnosisObs.keySet(), resubmittedObs);
            for (Integer obsId : obsToVoid) {
                submissionActions.modifyObs(existingDiagnosisObs.get(obsId), null, null, null, null, null);
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } catch (InvalidActionException e) {
        throw new IllegalStateException(e);
    }
}
Also used : Obs(org.openmrs.Obs) InvalidActionException(org.openmrs.module.htmlformentry.InvalidActionException) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) IOException(java.io.IOException) Diagnosis(org.openmrs.module.emrapi.diagnosis.Diagnosis) FormSubmissionActions(org.openmrs.module.htmlformentry.FormSubmissionActions) HashSet(java.util.HashSet)

Example 3 with DiagnosisMetadata

use of org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata in project openmrs-module-coreapps by openmrs.

the class ParserEncounterIntoSimpleObjects method parseObservations.

public ParsedObs parseObservations(Locale locale) {
    DiagnosisMetadata diagnosisMetadata = emrApiProperties.getDiagnosisMetadata();
    DispositionDescriptor dispositionDescriptor = null;
    try {
        dispositionDescriptor = dispositionService.getDispositionDescriptor();
    } catch (IllegalStateException ex) {
    // No problem. We do not require dispositions to be configured here
    }
    ParsedObs parsedObs = new ParsedObs();
    for (Obs obs : encounter.getObsAtTopLevel(false)) {
        if (diagnosisMetadata.isDiagnosis(obs)) {
            parsedObs.getDiagnoses().add(parseDiagnosis(diagnosisMetadata, obs));
        } else if (dispositionDescriptor != null && dispositionDescriptor.isDisposition(obs)) {
            parsedObs.getDispositions().add(parseDisposition(dispositionDescriptor, obs, locale));
        } else {
            parsedObs.getObs().add(parseObs(obs, locale));
        }
    }
    // just sort the obs by obsId--not perfect, but a decent "natural" object
    Collections.sort(parsedObs.getObs(), new Comparator<SimpleObject>() {

        @Override
        public int compare(SimpleObject o1, SimpleObject o2) {
            return (Integer) o1.get("obsId") < (Integer) o2.get("obsId") ? -1 : 1;
        }
    });
    Collections.sort(parsedObs.getDiagnoses(), new Comparator<SimpleObject>() {

        @Override
        public int compare(SimpleObject o1, SimpleObject o2) {
            Integer order1 = (Integer) o1.get("order");
            Integer order2 = (Integer) o2.get("order");
            return order1 - order2;
        }
    });
    return parsedObs;
}
Also used : Obs(org.openmrs.Obs) SimpleObject(org.openmrs.ui.framework.SimpleObject) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) DispositionDescriptor(org.openmrs.module.emrapi.disposition.DispositionDescriptor)

Example 4 with DiagnosisMetadata

use of org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata in project openmrs-module-coreapps by openmrs.

the class EncounterDiagnosesTagHandlerComponentTest method testHandleSubmissionHandlesValidSubmissionEnteringForm.

@Test
public void testHandleSubmissionHandlesValidSubmissionEnteringForm() throws Exception {
    final int codedConceptId = 11;
    ObjectMapper jackson = new ObjectMapper();
    ArrayNode json = jackson.createArrayNode();
    ObjectNode diagnosisNode = json.addObject();
    diagnosisNode.put("certainty", "PRESUMED");
    diagnosisNode.put("order", "PRIMARY");
    diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.CONCEPT_PREFIX + codedConceptId);
    final String jsonToSubmit = jackson.writeValueAsString(json);
    final DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();
    final Date date = new Date();
    new RegressionTestHelper() {

        @Override
        public String getXmlDatasetPath() {
            return "";
        }

        @Override
        public String getFormName() {
            return "encounterDiagnosesSimpleForm";
        }

        @Override
        public Map<String, Object> getFormEntrySessionAttributes() {
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("uiUtils", new TestUiUtils() {

                @Override
                public String includeFragment(String providerName, String fragmentId, Map<String, Object> config) throws PageAction {
                    return "[[ included fragment " + providerName + "." + fragmentId + " here ]]";
                }
            });
            return attributes;
        }

        @Override
        public String[] widgetLabels() {
            return new String[] { "Date:", "Location:", "Provider:", "Encounter Type:" };
        }

        @Override
        public void setupRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Date:"), dateAsString(date));
            request.setParameter(widgets.get("Location:"), "2");
            request.setParameter(widgets.get("Provider:"), "1");
            request.setParameter(widgets.get("Encounter Type:"), "1");
            request.setParameter("encounterDiagnoses", jsonToSubmit);
        }

        @Override
        public void testResults(SubmissionResults results) {
            results.assertNoErrors();
            results.assertEncounterCreated();
            results.assertProvider(1);
            results.assertLocation(2);
            results.assertEncounterType(1);
            results.assertObsCreatedCount(1);
            results.assertObsGroupCreated(dmd.getDiagnosisSetConcept().getConceptId(), dmd.getDiagnosisCertaintyConcept().getId(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED), dmd.getDiagnosisOrderConcept().getId(), dmd.getConceptFor(Diagnosis.Order.PRIMARY), dmd.getCodedDiagnosisConcept().getId(), Context.getConceptService().getConcept(codedConceptId));
        }
    }.run();
}
Also used : ObjectNode(org.codehaus.jackson.node.ObjectNode) TestUiUtils(org.openmrs.module.appui.TestUiUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) Date(java.util.Date) ArrayNode(org.codehaus.jackson.node.ArrayNode) HashMap(java.util.HashMap) Map(java.util.Map) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) RegressionTestHelper(org.openmrs.module.htmlformentry.RegressionTestHelper) Test(org.junit.Test) BaseModuleWebContextSensitiveTest(org.openmrs.web.test.BaseModuleWebContextSensitiveTest)

Example 5 with DiagnosisMetadata

use of org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata in project openmrs-module-coreapps by openmrs.

the class EncounterDiagnosesTagHandlerComponentTest method testHandleSubmissionHandlesValidSubmissionEditingForm.

@Test
public void testHandleSubmissionHandlesValidSubmissionEditingForm() throws Exception {
    final DiagnosisMetadata dmd = emrApiProperties.getDiagnosisMetadata();
    final Date date = new Date();
    // first, create an encounter
    final Concept malaria = conceptService.getConcept(11);
    final Patient patient = patientService.getPatient(8);
    final Encounter existingEncounter = new Encounter();
    existingEncounter.setEncounterType(new EncounterType(1));
    existingEncounter.setPatient(patient);
    existingEncounter.setEncounterDatetime(date);
    existingEncounter.setLocation(locationService.getLocation(2));
    Obs primaryDiagnosis = dmd.buildDiagnosisObsGroup(new Diagnosis(new CodedOrFreeTextAnswer(malaria), Diagnosis.Order.PRIMARY));
    Obs secondaryDiagnosis = dmd.buildDiagnosisObsGroup(new Diagnosis(new CodedOrFreeTextAnswer("Unknown disease"), Diagnosis.Order.SECONDARY));
    existingEncounter.addObs(primaryDiagnosis);
    existingEncounter.addObs(secondaryDiagnosis);
    encounterService.saveEncounter(existingEncounter);
    ObjectMapper jackson = new ObjectMapper();
    ArrayNode json = jackson.createArrayNode();
    {
        // change the existing primary diagnosis from PRESUMED to CONFIRMED
        ObjectNode diagnosisNode = json.addObject();
        diagnosisNode.put("certainty", "CONFIRMED");
        diagnosisNode.put("order", "PRIMARY");
        diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.CONCEPT_PREFIX + "11");
        diagnosisNode.put("existingObs", primaryDiagnosis.getObsId());
    }
    {
        // this is a new diagnosis
        ObjectNode diagnosisNode = json.addObject();
        diagnosisNode.put("certainty", "PRESUMED");
        diagnosisNode.put("order", "SECONDARY");
        diagnosisNode.put("diagnosis", CodedOrFreeTextAnswer.NON_CODED_PREFIX + "I had spelled it wrong before");
    }
    final String jsonToSubmit = jackson.writeValueAsString(json);
    new RegressionTestHelper() {

        @Override
        public String getXmlDatasetPath() {
            return "";
        }

        @Override
        public String getFormName() {
            return "encounterDiagnosesSimpleForm";
        }

        @Override
        public Map<String, Object> getFormEntrySessionAttributes() {
            Map<String, Object> attributes = new HashMap<String, Object>();
            attributes.put("uiUtils", new TestUiUtils() {

                @Override
                public String includeFragment(String providerName, String fragmentId, Map<String, Object> config) throws PageAction {
                    return "[[ included fragment " + providerName + "." + fragmentId + " here ]]";
                }
            });
            return attributes;
        }

        @Override
        public Patient getPatientToView() throws Exception {
            return patient;
        }

        @Override
        public Encounter getEncounterToEdit() {
            return existingEncounter;
        }

        @Override
        public String[] widgetLabelsForEdit() {
            return new String[] { "Date:", "Location:", "Provider:", "Encounter Type:" };
        }

        @Override
        public void setupEditRequest(MockHttpServletRequest request, Map<String, String> widgets) {
            request.setParameter(widgets.get("Date:"), dateAsString(date));
            request.setParameter(widgets.get("Location:"), "2");
            request.setParameter(widgets.get("Provider:"), "1");
            request.setParameter(widgets.get("Encounter Type:"), "1");
            request.setParameter("encounterDiagnoses", jsonToSubmit);
        }

        @Override
        public void testEditFormHtml(String html) {
            System.out.println(html);
        }

        @Override
        public void testEditedResults(SubmissionResults results) {
            results.assertNoErrors();
            results.assertEncounterEdited();
            List<Obs> diagnoses = new ArrayList<Obs>();
            for (Obs obs : results.getEncounterCreated().getObsAtTopLevel(true)) {
                if (dmd.isDiagnosis(obs)) {
                    diagnoses.add(obs);
                }
            }
            Matcher<Obs> newPrimary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withNonVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.CONFIRMED)).withVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withNonVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.PRIMARY)).withNonVoidedObs(dmd.getCodedDiagnosisConcept(), malaria);
            Matcher<Obs> newSecondary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withNonVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withNonVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.SECONDARY)).withNonVoidedObs(dmd.getNonCodedDiagnosisConcept(), "I had spelled it wrong before");
            Matcher<Obs> oldSecondary = new ObsGroupMatcher().withGroupingConcept(dmd.getDiagnosisSetConcept()).withVoidedObs(dmd.getDiagnosisCertaintyConcept(), dmd.getConceptFor(Diagnosis.Certainty.PRESUMED)).withVoidedObs(dmd.getDiagnosisOrderConcept(), dmd.getConceptFor(Diagnosis.Order.SECONDARY)).withVoidedObs(dmd.getNonCodedDiagnosisConcept(), "Unknown disease").thatIsVoided();
            assertThat(diagnoses.size(), is(3));
            assertThat(diagnoses, containsInAnyOrder(newPrimary, newSecondary, oldSecondary));
        }
    }.run();
}
Also used : ObsGroupMatcher(org.openmrs.module.emrapi.matcher.ObsGroupMatcher) Matcher(org.hamcrest.Matcher) Encounter(org.openmrs.Encounter) ArrayList(java.util.ArrayList) List(java.util.List) Diagnosis(org.openmrs.module.emrapi.diagnosis.Diagnosis) ArrayNode(org.codehaus.jackson.node.ArrayNode) ObjectMapper(org.codehaus.jackson.map.ObjectMapper) Concept(org.openmrs.Concept) Obs(org.openmrs.Obs) ObjectNode(org.codehaus.jackson.node.ObjectNode) TestUiUtils(org.openmrs.module.appui.TestUiUtils) MockHttpServletRequest(org.springframework.mock.web.MockHttpServletRequest) DiagnosisMetadata(org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata) Patient(org.openmrs.Patient) CodedOrFreeTextAnswer(org.openmrs.module.emrapi.diagnosis.CodedOrFreeTextAnswer) Date(java.util.Date) EncounterType(org.openmrs.EncounterType) HashMap(java.util.HashMap) Map(java.util.Map) ObsGroupMatcher(org.openmrs.module.emrapi.matcher.ObsGroupMatcher) RegressionTestHelper(org.openmrs.module.htmlformentry.RegressionTestHelper) Test(org.junit.Test) BaseModuleWebContextSensitiveTest(org.openmrs.web.test.BaseModuleWebContextSensitiveTest)

Aggregations

DiagnosisMetadata (org.openmrs.module.emrapi.diagnosis.DiagnosisMetadata)6 Obs (org.openmrs.Obs)4 Test (org.junit.Test)3 Diagnosis (org.openmrs.module.emrapi.diagnosis.Diagnosis)3 Date (java.util.Date)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Map (java.util.Map)2 ObjectMapper (org.codehaus.jackson.map.ObjectMapper)2 ArrayNode (org.codehaus.jackson.node.ArrayNode)2 ObjectNode (org.codehaus.jackson.node.ObjectNode)2 TestUiUtils (org.openmrs.module.appui.TestUiUtils)2 CodedOrFreeTextAnswer (org.openmrs.module.emrapi.diagnosis.CodedOrFreeTextAnswer)2 RegressionTestHelper (org.openmrs.module.htmlformentry.RegressionTestHelper)2 BaseModuleWebContextSensitiveTest (org.openmrs.web.test.BaseModuleWebContextSensitiveTest)2 MockHttpServletRequest (org.springframework.mock.web.MockHttpServletRequest)2 IOException (java.io.IOException)1 ArrayList (java.util.ArrayList)1 HashSet (java.util.HashSet)1 Matcher (org.hamcrest.Matcher)1