/** @see Encounter#getAllObs(null) */
  @Test
  @Verifies(
      value = "should get both parent and child with child directly on encounter",
      method = "getAllObs(null)")
  public void getAllObs_shouldGetBothParentAndChildWithChildDirectlyOnEncounter() throws Exception {
    Encounter enc = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    enc.addObs(parentObs);

    // add a child to the obs and make sure that now that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // add the child obs directly to the encounter as well
    childObs.setEncounter(enc);
    enc.addObs(childObs);

    // do the check
    assertEquals(2, enc.getAllObs(true).size());

    // this should return one of each -- the obsGroup and the child (because encounter_id is
    // populated in the child Obs):
    int numberOfChildObs = 0;
    int numberofParentObs = 0;
    for (Obs oTmp : enc.getAllObs(false)) {
      if (oTmp.isObsGrouping()) numberofParentObs++;
      else numberOfChildObs++;
    }
    assertEquals(1, numberOfChildObs);
    assertEquals(1, numberofParentObs);
  }
Beispiel #2
0
 /**
  * Convenience method that returns related Obs If the Obs argument is not an ObsGroup: a Set<Obs>
  * will be returned containing all of the children of this Obs' parent that are not ObsGroups
  * themselves. This will include this Obs by default, unless getObsGroup() returns null, in which
  * case an empty set is returned. If the Obs argument is an ObsGroup: a Set<Obs> will be returned
  * containing 1. all of this Obs' group members, and 2. all ancestor Obs that are not themselves
  * obsGroups.
  *
  * @return Set<Obs>
  */
 public Set<Obs> getRelatedObservations() {
   Set<Obs> ret = new HashSet<Obs>();
   if (this.isObsGrouping()) {
     ret.addAll(this.getGroupMembers());
     Obs parentObs = this;
     while (parentObs.getObsGroup() != null) {
       for (Obs obsSibling : parentObs.getObsGroup().getGroupMembers()) {
         if (!obsSibling.isObsGrouping()) ret.add(obsSibling);
       }
       parentObs = parentObs.getObsGroup();
     }
   } else if (this.getObsGroup() != null) {
     for (Obs obsSibling : this.getObsGroup().getGroupMembers()) {
       if (!obsSibling.isObsGrouping()) ret.add(obsSibling);
     }
   }
   return ret;
 }
 /** @return the number of obs groups in encounterCreated (0 if no encounter was created) */
 public int getObsGroupCreatedCount() {
   if (encounterCreated == null) return 0;
   Collection<Obs> temp = encounterCreated.getAllObs();
   if (temp == null) return 0;
   int count = 0;
   for (Obs o : temp) {
     if (o.isObsGrouping()) ++count;
   }
   return count;
 }
  /** @see Encounter#getObs() */
  @Test
  @Verifies(value = "should get obs with two levels of hierarchy", method = "getObs()")
  public void getObs_shouldGetObsWithTwoLevelsOfHierarchy() throws Exception {
    Encounter enc = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    enc.addObs(parentObs);

    // add a child to the obs and make sure that now that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // add the child obs directly to the encounter as well
    childObs.setEncounter(enc);
    enc.addObs(childObs);

    // make the obs two levels deep
    Obs grandChildObsOne = new Obs();
    Obs grandChildObsTwo = new Obs();
    childObs.addGroupMember(grandChildObsOne);
    childObs.addGroupMember(grandChildObsTwo);

    /// now getObs() should return the two leaf obs 2 levels down:
    assertEquals(2, enc.getObs().size());
    assertTrue(enc.getObs().contains(grandChildObsOne));
    assertTrue(enc.getObs().contains(grandChildObsTwo));

    // now grandChildObsOne isn't a leaf, it holds greatGrandChildObsOne, but the size of the set
    // returned shouldn't change:
    Obs greatGrandChildObsOne = new Obs();
    grandChildObsOne.addGroupMember(greatGrandChildObsOne);
    assertEquals(2, enc.getObs().size());
    assertTrue(enc.getObs().contains(greatGrandChildObsOne));
    assertTrue(enc.getObs().contains(grandChildObsTwo));

    // add a sibling to one of the leaves.  Add leaf to grandChildObsOne:
    Obs greatGrandChildObsTwo = new Obs();
    grandChildObsOne.addGroupMember(greatGrandChildObsTwo);

    // now getObs() should return a set of size 3:
    assertEquals(3, enc.getObs().size());

    // make sure none of them are grouping obs
    for (Obs oTmp : enc.getObs()) {
      assertFalse(oTmp.isObsGrouping());
    }
    assertTrue(enc.getObs().contains(greatGrandChildObsOne));
    assertTrue(enc.getObs().contains(greatGrandChildObsTwo));
    assertTrue(enc.getObs().contains(grandChildObsTwo));
  }
  public static Set<Obs> generateObsSinglesFromSearchResults() {
    SearchAPI searchAPI = SearchAPI.getInstance();
    Set<Obs> obsSingles = new HashSet<Obs>();
    for (ChartListItem item : searchAPI.getResults()) {
      if (item != null && item instanceof ObsItem && ((ObsItem) item).getObsId() != null) {
        int itemObsId = ((ObsItem) item).getObsId();

        Obs obs = Context.getObsService().getObs(itemObsId);
        if (obs != null && obs.getObsGroup() == null && !obs.isObsGrouping()) {
          obsSingles.add(Context.getObsService().getObs(itemObsId));
        }
      }
    }
    return obsSingles;
  }
  @Test
  public void shouldAddDiagnosesAdObservation() throws Exception {
    executeDataSet("baseMetaData.xml");
    executeDataSet("diagnosisMetaData.xml");
    executeDataSet("shouldAddDiagnosisAsObservation.xml");
    String cancerDiagnosisUuid = "d102c80f-1yz9-4da3-bb88-8122ce8868dh";
    String encounterDateTime = "2005-01-02T00:00:00.000+0000";
    String diagnosisDateTime = "2005-01-02T01:00:00.000+0000";
    String postData =
        "{"
            + "\"patientUuid\" : \"a76e8d23-0c38-408c-b2a8-ea5540f01b51\", "
            + "\"visitTypeUuid\" : \"b45ca846-c79a-11e2-b0c0-8e397087571c\", "
            + "\"encounterTypeUuid\": \"2b377dba-62c3-4e53-91ef-b51c68899891\", "
            + "\"encounterDateTime\" : \""
            + encounterDateTime
            + "\", "
            + "\"diagnoses\":["
            + "{\"order\":\"PRIMARY\", \"certainty\": \"CONFIRMED\", \"codedAnswer\": { \"uuid\": \""
            + cancerDiagnosisUuid
            + "\"}, \"diagnosisDateTime\": \""
            + diagnosisDateTime
            + "\" }"
            + "]"
            + "}";

    EncounterTransaction response =
        deserialize(
            handle(newPostRequest("/rest/emrapi/encounter", postData)), EncounterTransaction.class);

    Visit visit = visitService.getVisitByUuid(response.getVisitUuid());
    Encounter encounter = visit.getEncounters().iterator().next();

    Set<Obs> obsAtTopLevel = encounter.getObsAtTopLevel(false);
    assertEquals(1, obsAtTopLevel.size());
    Obs parentObservation = obsAtTopLevel.iterator().next();
    assertTrue(parentObservation.isObsGrouping());
    assertEquals(
        DateUtils.parseDate(diagnosisDateTime, dateTimeFormat), parentObservation.getObsDatetime());

    Set<Obs> diagnosisObservationGroupMembers = parentObservation.getGroupMembers();
    assertEquals(3, diagnosisObservationGroupMembers.size());
    ArrayList<String> valueCodedNames = getValuCodedNames(diagnosisObservationGroupMembers);
    assertTrue(valueCodedNames.contains("Confirmed"));
    assertTrue(valueCodedNames.contains("Primary"));
    assertTrue(valueCodedNames.contains("Cancer"));
  }
  /** @see Encounter#getObs() */
  @Test
  @Verifies(value = "should only get child obs", method = "getObs()")
  public void getObs_shouldOnlyGetChildObs() throws Exception {
    Encounter encounter = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    encounter.addObs(parentObs);

    // add a child to the obs and make sure that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // obsGroup should recurse and ONLY the child obs should be picked up:
    assertEquals(1, encounter.getObs().size());
    // make sure that the obs is the oChild
    Obs obsInEncounter = (Obs) encounter.getObs().toArray()[0];
    assertTrue(childObs.equals(obsInEncounter));
    assertFalse(obsInEncounter.isObsGrouping());
  }
  /** @see Encounter#getAllObs(null) */
  @Test
  @Verifies(value = "should get both parent and child obs", method = "getAllObs(null)")
  public void getAllObs_shouldGetBothParentAndChildObs() throws Exception {
    Encounter encounter = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    encounter.addObs(parentObs);

    // add a child to the obs and make sure that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // assert that the parent obs is returned
    assertNotNull(encounter.getAllObs(true));
    assertEquals(1, encounter.getAllObs(true).size());
    assertNotNull(encounter.getAllObs(false));
    assertEquals(1, encounter.getAllObs(false).size());
    Obs obsInEncounter = (Obs) encounter.getAllObs(false).toArray()[0];
    assertTrue(obsInEncounter.isObsGrouping());
  }
  /**
   * Column headers must be unique to avoid clobbering and to ensure it is clear which columns are
   * grouped together by obsgroup. As such, duplicate concepts at the parent level or duplicate
   * concepts in the same obs group are given a unique occurrence number. For instance, in an obs
   * group Functional Review Of Symptoms, there might be two child obs with the concept Symptom
   * Present. To distinguish them, one is given an occurrence number of 1 and the next an occurrence
   * number of 2.
   *
   * @param fieldMap
   * @param obs
   * @return Map<Obs, Integer> the filled in fieldMap
   */
  public static Map<Obs, Integer> addChildrenObsToFieldMap(Map<Obs, Integer> fieldMap, Obs obs) {

    if (obs != null && obs.isObsGrouping()) {

      Set<Obs> childSet = obs.getGroupMembers();
      List<Obs> children = new ArrayList<Obs>(childSet);

      Map<Concept, Integer> childMap = new HashMap<Concept, Integer>();
      for (Obs o : children) {
        // check for duplicate concepts among this batch of children
        Integer occurrence =
            (childMap.get(o.getConcept()) != null) ? childMap.get(o.getConcept()) : 0;
        occurrence++;
        childMap.put(o.getConcept(), occurrence);

        fieldMap.put(o, occurrence);
        addChildrenObsToFieldMap(fieldMap, o);
      }
    }

    return fieldMap;
  }
  /** @see Encounter#getObs() */
  @Test
  @Verifies(value = "should not get child obs if child also on encounter", method = "getObs()")
  public void getObs_shouldNotGetChildObsIfChildAlsoOnEncounter() throws Exception {
    Encounter encounter = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    encounter.addObs(parentObs);

    // add a child to the obs and make sure that now that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // add the child obs directly to the encounter as well
    childObs.setEncounter(encounter);
    encounter.addObs(childObs);

    // do the check
    assertEquals(1, encounter.getObs().size());
    Obs obsInEncounter = (Obs) encounter.getObs().toArray()[0];
    assertFalse(obsInEncounter.isObsGrouping());
  }
  /** @see Encounter#getObsAtTopLevel(null) */
  @Test
  @Verifies(value = "should only get parents obs", method = "getObsAtTopLevel(null)")
  public void getObsAtTopLevel_shouldOnlyGetParentsObs() throws Exception {
    Encounter encounter = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    encounter.addObs(parentObs);

    // add a child to the obs and make sure that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // assert that the parent obs is returned by getObsAtTopLevel()
    assertNotNull(encounter.getObsAtTopLevel(true));
    assertEquals(1, encounter.getObsAtTopLevel(true).size());
    assertNotNull(encounter.getObsAtTopLevel(false));
    assertEquals(1, encounter.getObsAtTopLevel(false).size());

    // make sure that the obs is the parent obs
    Obs obsInEncounter = (Obs) encounter.getObsAtTopLevel(false).toArray()[0];
    assertTrue(obsInEncounter.isObsGrouping());
  }
  /** @see Encounter#getObsAtTopLevel(null) */
  @Test
  @Verifies(
      value = "should only return the grouped top level obs",
      method = "getObsAtTopLevel(null)")
  public void getObsAtTopLevel_shouldOnlyReturnTheGroupedTopLevelObs() throws Exception {
    Encounter encounter = new Encounter();

    // create and add an Obs
    Obs parentObs = new Obs();
    encounter.addObs(parentObs);

    // add a child to the obs and make sure that now that the Obs is an ObsGroup with one child:
    Obs childObs = new Obs();
    parentObs.addGroupMember(childObs);

    // add the child obs directly to the encounter as well
    childObs.setEncounter(encounter);
    encounter.addObs(childObs);

    // do the check
    assertEquals(1, encounter.getObsAtTopLevel(false).size());
    Obs obsInEncounter = (Obs) encounter.getObsAtTopLevel(false).toArray()[0];
    assertTrue(obsInEncounter.isObsGrouping());
  }
    /**
     *
     * Returns the encounter with the obs that aren't used when populating form are removed.
     * This *doesn't* save the encounter.
     * TODO: handle Orders?
     *
     * @param e
     * @param htmlform
     * @return
     * @throws Exception
     */
    public static Encounter trimEncounterToMatchForm(Encounter e, HtmlForm htmlform) throws Exception {

       //this should move existing obs from session to tag handlers.
        FormEntrySession session = new FormEntrySession(e.getPatient(), e, FormEntryContext.Mode.VIEW, htmlform, null); // session gets a null HttpSession
        session.getHtmlToDisplay();

        if (log.isDebugEnabled()){
            Map<Concept, List<Obs>>  map = session.getContext().getExistingObs();
            if (map != null){
                for (Map.Entry<Concept, List<Obs>> existingObs : map.entrySet()){
                    List<Obs> oList = existingObs.getValue();
                    for (Obs oInner : oList)
                        log.debug("Obs in existingObs " + existingObs.getKey() + " " + oInner.getConcept());
                }
            }
            Map<Obs, Set<Obs>> map2 = session.getContext().getExistingObsInGroups();
            if (map2 != null){
                for (Map.Entry<Obs, Set<Obs>> existingObsInGroups : map2.entrySet()){
                    Set<Obs> oList = existingObsInGroups.getValue();
                    for (Obs oInner : oList)
                        log.debug("Obs in existingObsInGroups " + existingObsInGroups.getKey().getConcept() + " " + oInner.getConcept());
                }
            }
        }
        Encounter ret = new Encounter();
        ret.setCreator(e.getCreator());
        ret.setEncounterDatetime(e.getEncounterDatetime());
        EncounterCompatibility.setProvider(ret, EncounterCompatibility.getProvider(e));
        ret.setLocation(e.getLocation());
        ret.setDateCreated(e.getDateCreated());
        ret.setPatient(e.getPatient());
        //renders new encounter unsave-able:
        ret.setEncounterId(e.getEncounterId());

        for (Obs oTest : e.getAllObs()){
            boolean found = false;
            if (session.getContext().getExistingObs() != null && !oTest.isObsGrouping()){
                List<Obs> obsList = session.getContext().getExistingObs().get(oTest.getConcept());
                if (obsList != null && obsList.size() > 0){
                    for (Obs o : obsList){
                        if (o.getObsId().equals(oTest.getObsId())){
                            found = true;
                            continue;
                        }
                    }
                }
            }
            if (!found && session.getContext().getExistingObsInGroups() != null){
                for (Map.Entry<Obs, Set<Obs>> mapEntry : session.getContext().getExistingObsInGroups().entrySet()){
                    if (mapEntry.getKey().equals(oTest)){
                        found = true;
                        continue;
                    } else {
                        Set<Obs> oSet = mapEntry.getValue();
                        //note: oSet.contains fails for some reason
                        for (Obs o:oSet){
                              if (o.getObsId().equals(oTest.getObsId())){
                                  found = true;
                                  continue;
                              }
                        }
                    }
                }
            }
            if (!found)
                ret.addObs(oTest);
        }
        session = null;
        return ret;
    }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldReturnEncounterCorrectly() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));

    // add a bunch of obs...
    TestUtil.addObs(e, 2474, Context.getConceptService().getConcept(656), date); // matches
    TestUtil.addObs(e, 3017, Context.getConceptService().getConcept(767), date); // matches
    TestUtil.addObs(e, 3032, new Date(), date); // matches
    TestUtil.addObs(e, 1, 5000, date); //   matches
    TestUtil.addObs(e, 2, 5000, date); // not in form schema
    TestUtil.addObs(e, 3, 5000, date); // not in form schema
    TestUtil.addObs(e, 6, "blah blah", date); //   matches
    // 1004 is ANOTHER ALLERGY CONSTRUCT, 1005 is HYPER-ALLERGY CODED, 1001 is PENICILLIN
    TestUtil.addObsGroup(
        e,
        1004,
        new Date(),
        1005,
        Context.getConceptService().getConcept(1001),
        new Date()); // matches
    // 7 IS ALLERGY CONSTRUCT, 1000 IS ALLERGY CODED, 1003 IS OPENMRS
    TestUtil.addObsGroup(
        e,
        7,
        new Date(),
        1000,
        Context.getConceptService().getConcept(1003),
        new Date()); // matches
    TestUtil.addObsGroup(
        e,
        1000,
        new Date(),
        7,
        Context.getConceptService().getConcept(1003),
        new Date()); // does not match
    Context.getEncounterService().saveEncounter(e);

    Form form = new Form();
    HtmlForm htmlform = new HtmlForm();
    htmlform.setForm(form);
    form.setEncounterType(new EncounterType());
    htmlform.setDateChanged(new Date());
    htmlform.setXmlData(
        new TestUtil()
            .loadXmlFromFile(
                XML_DATASET_PATH + "returnSectionsAndConceptsInSectionsTestFormWithGroups.xml"));
    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // this is going to test out the voided state of the obs in the encounter after processing:
    Assert.assertTrue(!e.isVoided());
    for (Obs o : e.getAllObs(true)) {
      if (o.getConcept().getConceptId().equals(2474)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(3017)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(3032)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(1)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(2)) Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(3)) Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(6)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(1004)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(1005)) Assert.assertTrue(o.isVoided());

      // obsGroups
      if (o.getConcept().getConceptId().equals(7) && o.isObsGrouping())
        Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(7) && !o.isObsGrouping())
        Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(1000) && o.isObsGrouping())
        Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(1000) && !o.isObsGrouping())
        Assert.assertTrue(o.isVoided());
    }
  }