@SuppressWarnings("unused")
  public static JSONObject createJsonObservation(Obs obs) {
    JSONObject jsonObs = new JSONObject();
    jsonObs.put("observation_id", obs.getObsId());
    jsonObs.put("concept_name", obs.getConcept().getDisplayString());

    Date obsDate = obs.getObsDatetime() == null ? new Date() : obs.getObsDatetime();

    SimpleDateFormat formatDateJava = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    String dateStr = obsDate.getTime() + "";

    jsonObs.put("date", dateStr);

    if (obs.getConcept().getDatatype().isNumeric()) { // ADD MORE DATATYPES

      ConceptNumeric conceptNumeric =
          Context.getConceptService().getConceptNumeric(obs.getConcept().getId());
      jsonObs.put("units_of_measurement", conceptNumeric.getUnits());
      jsonObs.put("absolute_high", conceptNumeric.getHiAbsolute());
      jsonObs.put("absolute_low", conceptNumeric.getLowAbsolute());
      jsonObs.put("critical_high", conceptNumeric.getHiCritical());
      jsonObs.put("critical_low", conceptNumeric.getLowCritical());
      jsonObs.put("normal_high", conceptNumeric.getHiNormal());
      jsonObs.put("normal_low", conceptNumeric.getLowNormal());
    }
    jsonObs.put("value_type", obs.getConcept().getDatatype().getName());

    jsonObs.put("value", obs.getValueAsString(Context.getLocale()));
    jsonObs.put("location", obs.getLocation().getDisplayString());
    jsonObs.put("creator", obs.getCreator().getDisplayString());
    Set<EncounterProvider> encounterProviders = obs.getEncounter().getEncounterProviders();

    if (encounterProviders != null && encounterProviders.iterator().hasNext()) {
      EncounterProvider provider = encounterProviders.iterator().next();
      if (provider.getProvider() != null) {
        jsonObs.put("provider", provider.getProvider().getName());
      }
    }

    SearchAPI searchAPI = SearchAPI.getInstance();
    if (!searchAPI.getSearchPhrase().getPhrase().equals("")
        && !searchAPI.getSearchPhrase().getPhrase().equals("*")) {
      for (ChartListItem item : searchAPI.getResults()) {
        if (item != null && item instanceof ObsItem && ((ObsItem) item).getObsId() != null) {
          if (((ObsItem) item).getObsId() == obs.getObsId()) {
            jsonObs.put("chosen", "true");
          }
        }
      }
    }

    return jsonObs;
  }
Exemplo n.º 2
0
  /**
   * Builds a coded result from an observation
   *
   * @param obs
   */
  public Result(Obs obs) {
    this(
        obs.getObsDatetime(),
        null,
        obs.getValueAsBoolean(),
        obs.getValueCoded(),
        obs.getValueDatetime(),
        obs.getValueNumeric(),
        obs.getValueText(),
        obs);

    Concept concept = obs.getConcept();
    ConceptDatatype conceptDatatype = null;

    if (concept != null) {
      conceptDatatype = concept.getDatatype();

      if (conceptDatatype == null) {
        return;
      }
      if (conceptDatatype.isCoded()) {
        this.datatype = Datatype.CODED;
      } else if (conceptDatatype.isNumeric()) {
        this.datatype = Datatype.NUMERIC;
      } else if (conceptDatatype.isDate()) {
        this.datatype = Datatype.DATETIME;
      } else if (conceptDatatype.isText()) {
        this.datatype = Datatype.TEXT;
      } else if (conceptDatatype.isBoolean()) {
        this.datatype = Datatype.BOOLEAN;
      }
    }
  }
    /**
     * Fails if there isn't an obs group with these exact characteristics
     *
     * @param groupingConceptId the concept id of the grouping obs
     * @param conceptIdsAndValues these parameters must be given in pairs, the first element of
     *     which is the conceptId of a child obs (Integer) and the second element of which is the
     *     value of the child obs
     */
    public void assertObsGroupCreated(int groupingConceptId, Object... conceptIdsAndValues) {
      // quick checks
      Assert.assertNotNull(encounterCreated);
      Collection<Obs> temp = encounterCreated.getAllObs();
      Assert.assertNotNull(temp);

      List<ObsValue> expected = new ArrayList<ObsValue>();
      for (int i = 0; i < conceptIdsAndValues.length; i += 2) {
        int conceptId = (Integer) conceptIdsAndValues[i];
        Object value = conceptIdsAndValues[i + 1];
        expected.add(new ObsValue(conceptId, value));
      }

      for (Obs o : temp) {
        if (o.getConcept().getConceptId() == groupingConceptId) {
          if (o.getValueCoded() != null
              || o.getValueComplex() != null
              || o.getValueDatetime() != null
              || o.getValueDrug() != null
              || o.getValueNumeric() != null
              || o.getValueText() != null) {
            Assert.fail(
                "Obs group with groupingConceptId "
                    + groupingConceptId
                    + " should has a non-null value");
          }
          if (TestUtil.isMatchingObsGroup(o, expected)) {
            return;
          }
        }
      }
      Assert.fail("Cannot find an obs group matching " + expected);
    }
 public void printEncounterCreated() {
   if (encounterCreated == null) {
     System.out.println("No encounter created");
   } else {
     System.out.println("=== Encounter created ===");
     System.out.println(
         "Created: "
             + encounterCreated.getDateCreated()
             + "  Edited: "
             + encounterCreated.getDateChanged());
     System.out.println("Date: " + encounterCreated.getEncounterDatetime());
     System.out.println("Location: " + encounterCreated.getLocation().getName());
     System.out.println("Provider: " + encounterCreated.getProvider().getPersonName());
     System.out.println("    (obs)");
     Collection<Obs> obs = encounterCreated.getAllObs(false);
     if (obs == null) {
       System.out.println("None");
     } else {
       for (Obs o : obs) {
         System.out.println(
             o.getConcept().getName() + " -> " + o.getValueAsString(Context.getLocale()));
       }
     }
   }
 }
  @Test
  public void shouldAddNewObservation() throws Exception {
    executeDataSet("shouldAddNewObservation.xml");
    String encounterDateTime = "2005-01-02T00:00:00.000+0000";
    String json =
        "{ \"patientUuid\" : \"a76e8d23-0c38-408c-b2a8-ea5540f01b51\", "
            + "\"visitTypeUuid\" : \"b45ca846-c79a-11e2-b0c0-8e397087571c\", "
            + "\"encounterTypeUuid\": \"2b377dba-62c3-4e53-91ef-b51c68899890\", "
            + "\"encounterDateTime\" : \""
            + encounterDateTime
            + "\", "
            + "\"observations\":["
            + "{\"concept\": {\"uuid\": \"d102c80f-1yz9-4da3-bb88-8122ce8868dd\"}, \"conceptName\":\"Should be Ignored\", \"value\":20}, "
            + "{\"concept\": {\"uuid\": \"8f8e7340-a067-11e3-a5e2-0800200c9a66\"}, \"value\": {\"uuid\": \"e7167090-a067-11e3-a5e2-0800200c9a66\"}}, "
            + "{\"concept\": {\"uuid\": \"e102c80f-1yz9-4da3-bb88-8122ce8868dd\"}, \"value\":\"text value\", \"comment\":\"overweight\"}]}";

    MockHttpServletResponse response1 = handle(newPostRequest("/rest/emrapi/encounter", json));

    EncounterTransaction response = deserialize(response1, EncounterTransaction.class);

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

    assertEquals(3, encounter.getObs().size());
    Iterator<Obs> obsIterator = encounter.getObs().iterator();

    Map<String, Obs> map = new HashMap<String, Obs>();
    while (obsIterator.hasNext()) {
      Obs obs = obsIterator.next();
      map.put(obs.getConcept().getDatatype().getHl7Abbreviation(), obs);
    }
    Obs textObservation = map.get(ConceptDatatype.TEXT);
    assertEquals("text value", textObservation.getValueText());
    assertEquals("a76e8d23-0c38-408c-b2a8-ea5540f01b51", textObservation.getPerson().getUuid());
    assertEquals("e102c80f-1yz9-4da3-bb88-8122ce8868dd", textObservation.getConcept().getUuid());
    assertEquals("f13d6fae-baa9-4553-955d-920098bec08f", textObservation.getEncounter().getUuid());
    assertEquals("overweight", textObservation.getComment());
    //        TODO : change the observation startTime logic to take current time as start time when
    // startTime is not passed by the client
    //        assertEquals(DateUtils.parseDate(encounterDateTime, dateTimeFormat),
    // textObservation.getObsDatetime());

    assertEquals(
        "e7167090-a067-11e3-a5e2-0800200c9a66",
        map.get(ConceptDatatype.CODED).getValueCoded().getUuid());
    assertEquals(new Double(20.0), map.get(ConceptDatatype.NUMERIC).getValueNumeric());
  }
    public boolean matches(Obs obs) {

      if (!obs.getConcept().getConceptId().equals(conceptId)) {
        return false;
      }

      return OpenmrsUtil.nullSafeEquals(
          TestUtil.valueAsStringHelper(value), obs.getValueAsString(Context.getLocale()));
    }
 private Obs findOrCreateObs(Obs diagnosisObs, Concept concept) {
   for (Obs o : diagnosisObs.getGroupMembers()) {
     if (concept.equals(o.getConcept())) {
       return o;
     }
   }
   Obs obs = new Obs();
   obs.setConcept(concept);
   return obs;
 }
 private List<Obs> getSavedDocuments(Set<Obs> allObs, String conceptUuid) {
   List<Obs> obsList = new ArrayList<>();
   for (Obs obs : allObs) {
     if (obs.getConcept().getUuid().equals(conceptUuid)) {
       obsList.add(obs);
     }
   }
   Collections.sort(obsList, new IdBasedComparator());
   return obsList;
 }
 public static List<Chemotherapy> generateChemotherapies(Patient patient) {
   List<Encounter> encounters =
       getEncountersByTreatment(patient, PatientPortalToolkitConstants.CHEMOTHERAPY_ENCOUNTER);
   List<Chemotherapy> chemotherapiesList = new ArrayList<Chemotherapy>();
   for (Encounter e : encounters) {
     Chemotherapy chemotherapy = new Chemotherapy();
     List<String> chemomedications = new ArrayList<String>();
     Set<Obs> obsList = e.getObs();
     chemotherapy.setEncounterUuid(e.getUuid());
     for (Obs o : obsList) {
       if (o.getConcept().getUuid().equals("8481b9da-74e3-45a9-9124-d69ab572d636"))
         chemomedications.add(o.getValueCoded().getName().getName());
       if (o.getConcept().getUuid().equals("85c3a99e-0598-4c63-912b-796dee9c75b2"))
         chemotherapy.setChemoStartDate(o.getValueDate());
       if (o.getConcept().getUuid().equals("7dd8b8aa-b0f1-4eb1-862d-b6d737bdd315"))
         chemotherapy.setChemoEndDate(o.getValueDate());
       if (o.getConcept().getUuid().equals("361b7f9b-a985-4b18-9055-03af3b41b8b3")) {
         if (o.getValueCoded().getUuid().equals("1065AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"))
           chemotherapy.setCentralLine(true);
         else chemotherapy.setCentralLine(false);
       }
       // doctors name
       if (o.getConcept().getUuid().equals("c2cb2220-c07d-47c6-a4df-e5918aac3fc2"))
         chemotherapy.setPcpName(o.getValueText());
       // doctors email
       if (o.getConcept().getUuid().equals("898a0028-8c65-4db9-a802-1577fce59864"))
         chemotherapy.setPcpEmail(o.getValueText());
       // doctors phone
       if (o.getConcept().getUuid().equals("9285b227-4054-4830-ac32-5ea78462e8c4"))
         chemotherapy.setPcpPhone(o.getValueText());
       if (o.getConcept().getUuid().equals("47d58999-d3b5-4869-a52e-841e2e6bdbb3"))
         chemotherapy.setInstitutionName(o.getValueText());
       if (o.getConcept().getUuid().equals("bfa752d6-2037-465e-b0a2-c4c2d485ec32"))
         chemotherapy.setInstitutionCity(o.getValueText());
       if (o.getConcept().getUuid().equals("34489100-487e-443a-bf27-1b6869fb9332"))
         chemotherapy.setInstitutionState(o.getValueText());
     }
     chemotherapy.setChemoMedications(chemomedications);
     chemotherapiesList.add(chemotherapy);
   }
   return chemotherapiesList;
 }
 public static List<Surgery> generateSurgeries(Patient patient) {
   List<Encounter> encounters =
       getEncountersByTreatment(patient, PatientPortalToolkitConstants.SURGERY_ENCOUNTER);
   List<Surgery> surgeriesList = new ArrayList<Surgery>();
   for (Encounter e : encounters) {
     Surgery surgery = new Surgery();
     List<String> surgeryTypes = new ArrayList<String>();
     Set<Obs> obsList = e.getObs();
     surgery.setEncounterUuid(e.getUuid());
     for (Obs o : obsList) {
       if (o.getConcept().getUuid().equals("d409122c-8a0b-4282-a17f-07abad81f278"))
         surgeryTypes.add(o.getValueCoded().getName().getName());
       if (o.getConcept().getUuid().equals("99ef1d68-05ed-4f37-b98b-c982e3574138")) {
         if (o.getValueCoded().getUuid().equals("1065AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"))
           surgery.setHasMajorComplications(true);
         else surgery.setHasMajorComplications(false);
       }
       if (o.getConcept().getUuid().equals("c2d9fca3-1e0b-4007-8c3c-b3ebb4e67963"))
         surgery.setMajorComplications(o.getValueText());
       if (o.getConcept().getUuid().equals("87a69397-65ef-4576-a709-ae0a526afd85"))
         surgery.setSurgeryDate(o.getValueDate());
       // doctors name
       if (o.getConcept().getUuid().equals("c2cb2220-c07d-47c6-a4df-e5918aac3fc2"))
         surgery.setPcpName(o.getValueText());
       // doctors email
       if (o.getConcept().getUuid().equals("898a0028-8c65-4db9-a802-1577fce59864"))
         surgery.setPcpEmail(o.getValueText());
       // doctors phone
       if (o.getConcept().getUuid().equals("9285b227-4054-4830-ac32-5ea78462e8c4"))
         surgery.setPcpPhone(o.getValueText());
       if (o.getConcept().getUuid().equals("47d58999-d3b5-4869-a52e-841e2e6bdbb3"))
         surgery.setInstitutionName(o.getValueText());
       if (o.getConcept().getUuid().equals("bfa752d6-2037-465e-b0a2-c4c2d485ec32"))
         surgery.setInstitutionCity(o.getValueText());
       if (o.getConcept().getUuid().equals("34489100-487e-443a-bf27-1b6869fb9332"))
         surgery.setInstitutionState(o.getValueText());
     }
     surgery.setSurgeryTypes(surgeryTypes);
     surgeriesList.add(surgery);
   }
   return surgeriesList;
 }
  /**
   * Iterate over all encounters to determine occurrence number based on concept duplication at same
   * level For instance, an obs group 'functional review of symptoms' might occur twice in the same
   * form In this case, it is important to maintain which children belong to which parent
   *
   * @param fieldMap
   * @param e the encounter to add to the fieldMap
   * @return fieldMap
   */
  public static Map<Obs, Integer> addEncounterToFieldMap(Map<Obs, Integer> fieldMap, Encounter e) {
    Map<Concept, Integer> parentMap = new HashMap<Concept, Integer>();

    for (Obs obs : e.getObsAtTopLevel(false)) {

      Integer occurrence =
          (parentMap.get(obs.getConcept()) != null) ? parentMap.get(obs.getConcept()) : 0;
      occurrence++;
      parentMap.put(obs.getConcept(), occurrence);

      // Add top level obs to the fieldMap
      fieldMap.put(obs, occurrence);

      // Add children observations to the fieldMap recursively.
      // fieldMap will have each obs with the occurrence number
      // for a given concept on a given level of the tree structure
      addChildrenObsToFieldMap(fieldMap, obs);
    }
    return fieldMap;
  }
Exemplo n.º 12
0
 /** @see java.util.Iterator#next() */
 public Map<String, Object> next() {
   Locale locale = Context.getLocale();
   Obs obs = iter.next();
   Map<String, Object> ret = new HashMap<String, Object>();
   ret.put("patientId", obs.getPersonId());
   ret.put("question", obs.getConcept().getName(locale, false));
   ret.put("questionConceptId", obs.getConcept().getConceptId());
   ret.put("answer", obs.getValueAsString(locale));
   if (obs.getValueCoded() != null) {
     ret.put("answerConceptId", obs.getValueCoded());
   }
   ret.put("obsDatetime", obs.getObsDatetime());
   if (obs.getEncounter() != null) {
     ret.put("encounterId", obs.getEncounter().getEncounterId());
   }
   if (obs.getObsGroup() != null) {
     ret.put("obsGroupId", obs.getObsGroup().getObsId());
   }
   return ret;
 }
  @Test
  public void shouldAddNewObservationGroup() throws Exception {
    executeDataSet("shouldAddNewObservation.xml");
    String encounterDateTime = "2005-01-02T00:00:00.000+0000";
    String observationTime = "2005-01-02T12:00:00.000+0000";
    String json =
        "{ \"patientUuid\" : \"a76e8d23-0c38-408c-b2a8-ea5540f01b51\", "
            + "\"visitTypeUuid\" : \"b45ca846-c79a-11e2-b0c0-8e397087571c\", "
            + "\"encounterTypeUuid\": \"2b377dba-62c3-4e53-91ef-b51c68899890\", "
            + "\"encounterDateTime\" : \""
            + encounterDateTime
            + "\", "
            + "\"observations\":["
            + "{\"concept\":{\"uuid\": \"e102c80f-1yz9-4da3-bb88-8122ce8868dd\"}, "
            + " \"groupMembers\" : [{\"concept\":{\"uuid\": \"d102c80f-1yz9-4da3-bb88-8122ce8868dd\"}, \"value\":20, \"comment\":\"overweight\", \"observationDateTime\": \""
            + observationTime
            + "\"}] }"
            + "]}";

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

    Visit visit = visitService.getVisitByUuid(response.getVisitUuid());
    Encounter encounter = (Encounter) visit.getEncounters().toArray()[0];

    assertEquals(1, encounter.getObs().size());
    Obs obs = (Obs) encounter.getAllObs().toArray()[0];
    assertEquals("e102c80f-1yz9-4da3-bb88-8122ce8868dd", obs.getConcept().getUuid());

    assertEquals(1, obs.getGroupMembers().size());
    Obs member = obs.getGroupMembers().iterator().next();
    assertEquals("d102c80f-1yz9-4da3-bb88-8122ce8868dd", member.getConcept().getUuid());
    assertEquals(new Double(20.0), member.getValueNumeric());
    assertEquals("a76e8d23-0c38-408c-b2a8-ea5540f01b51", member.getPerson().getUuid());
    assertEquals("f13d6fae-baa9-4553-955d-920098bec08f", member.getEncounter().getUuid());
    assertEquals("overweight", member.getComment());
    assertEquals(
        new SimpleDateFormat(dateTimeFormat).parse(observationTime), member.getObsDatetime());
  }
  /**
   * 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;
  }
 private boolean hasIgnoredConcept(Obs obs) {
   String globalPropertyValue =
       globalPropertyLookUpService.getGlobalPropertyValue(
           MRSProperties.GLOBAL_PROPERTY_IGNORED_CONCEPT_LIST);
   if (StringUtils.isBlank(globalPropertyValue)) return false;
   List<String> conceptIds = asList(StringUtils.split(globalPropertyValue, ","));
   for (String conceptId : conceptIds) {
     if (obs.getConcept().getId().equals(Integer.parseInt(conceptId.trim()))) {
       return true;
     }
   }
   return false;
 }
 private FHIRResource mapObservation(
     Obs openmrsObs, Encounter fhirEncounter, SystemProperties systemProperties) {
   FHIRResource fhirObservationResource =
       observationBuilder.buildObservationResource(
           fhirEncounter,
           systemProperties,
           openmrsObs.getUuid(),
           openmrsObs.getConcept().getName().getName());
   Observation fhirObservation = (Observation) fhirObservationResource.getResource();
   fhirObservation.setStatus(ObservationStatusEnum.PRELIMINARY);
   mapCode(openmrsObs, fhirObservation);
   mapValue(openmrsObs, fhirObservation);
   return fhirObservationResource;
 }
  @Test
  public void shouldChangeObservationsOfPreviousEncounters() throws Exception {
    Date visitStartDate = getDateFromString("2014-06-22 00:00:00");
    Date encounterDate = getDateFromString("2014-06-23 00:00:00");

    List<Document> documents = new ArrayList<>();
    documents.add(
        new Document(
            "/radiology/foo.jpg",
            null,
            "5f596de5-5caa-11e3-a4c0-0800271c1b75",
            "6d0ae386-707a-4629-9850-f15206e63kj0",
            encounterDate,
            false));

    VisitDocumentRequest visitDocumentRequest =
        new VisitDocumentRequest(
            patientUUID,
            firstVisitUuid,
            visitTypeUUID,
            visitStartDate,
            null,
            secondEncounterTypeUUID,
            encounterDate,
            documents,
            secondProviderUuid,
            secondLocationUuid,
            null);
    executeDataSet("visitDocumentData.xml");
    visitDocumentService.upload(visitDocumentRequest);

    Context.flushSession();
    Context.clearSession();

    Encounter encounter = encounterService.getEncounterByUuid(secondEncounterUuid);
    for (Obs obs : encounter.getAllObs(true)) {
      if (obs.getUuid().equals("6d0ae386-707a-4629-9850-f15606e63666")
          || obs.getUuid().equals("6d0ae386-707a-4629-9850-f15206e63kj0")) {
        assertThat(obs.getVoided(), is(true));
      }
    }

    Obs savedDoc = getSavedDocument(encounter.getAllObs(), "5f596de5-5caa-11e3-a4c0-0800271c1b75");

    assertNotNull(savedDoc);
    assertThat(savedDoc.getConcept().getId(), is(333));
    assertThat(
        savedDoc.getGroupMembers().iterator().next().getValueText(), is("/radiology/foo.jpg"));
    assertEquals(FIRST_LOCATION_UUID, encounter.getLocation().getUuid());
  }
    private void assertObsExists(boolean lookForVoided, int conceptId, Object value) {
      // quick checks
      Assert.assertNotNull(encounterCreated);
      Collection<Obs> temp = encounterCreated.getAllObs(lookForVoided);
      Assert.assertNotNull(temp);

      String valueAsString = TestUtil.valueAsStringHelper(value);
      for (Obs obs : temp) {
        if (lookForVoided && !obs.isVoided()) continue;
        if (obs.getConcept().getConceptId() == conceptId) {
          if (valueAsString == null) return;
          if (valueAsString.equals(obs.getValueAsString(Context.getLocale()))) return;
        }
      }
      Assert.fail("Could not find obs with conceptId " + conceptId + " and value " + valueAsString);
    }
  public static Set<String> generateDatatypesFromResults() {
    Set<String> res = new HashSet<String>();
    SearchAPI searchAPI = SearchAPI.getInstance();

    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) {
          res.add(obs.getConcept().getDatatype().getName());
        }
      }
    }
    return res;
  }
  /**
   * Auto generated method comment
   *
   * @param obs
   * @param conceptId
   * @return
   */
  public static String convsetObsValueByConcept(Obs obs, Integer conceptId) {
    String res = "-";
    try {
      if (obs != null) {
        for (Obs ob : obs.getGroupMembers()) {
          if (ob.getConcept().getConceptId() == conceptId.intValue()) {
            res = ob.getValueAsString(Context.getLocale());
            break;
          }
        }
      }
    } catch (Exception e) {
      log.error(">>>>>>>>>>>>>>>>>>>VCT>>Module>>Tag>>>> An error occured : " + e.getMessage());
      e.printStackTrace();
    }

    return res;
  }
 public static List<Radiation> generateRadiations(Patient patient) {
   List<Encounter> encounters =
       getEncountersByTreatment(patient, PatientPortalToolkitConstants.RADIATION_ENCOUNTER);
   List<Radiation> radiationsList = new ArrayList<Radiation>();
   for (Encounter e : encounters) {
     Radiation radiation = new Radiation();
     List<String> radiationTypes = new ArrayList<String>();
     Set<Obs> obsList = e.getObs();
     radiation.setEncounterUuid(e.getUuid());
     for (Obs o : obsList) {
       if (o.getConcept().getUuid().equals("42fb7bb5-f840-4518-814c-893813211cba"))
         radiationTypes.add(o.getValueCoded().getName().getName());
       if (o.getConcept().getUuid().equals("85c3a99e-0598-4c63-912b-796dee9c75b2"))
         radiation.setStartDate(o.getValueDate());
       if (o.getConcept().getUuid().equals("7dd8b8aa-b0f1-4eb1-862d-b6d737bdd315"))
         radiation.setEndDate(o.getValueDate());
       // doctors name
       if (o.getConcept().getUuid().equals("c2cb2220-c07d-47c6-a4df-e5918aac3fc2"))
         radiation.setPcpName(o.getValueText());
       // doctors email
       if (o.getConcept().getUuid().equals("898a0028-8c65-4db9-a802-1577fce59864"))
         radiation.setPcpEmail(o.getValueText());
       // doctors phone
       if (o.getConcept().getUuid().equals("9285b227-4054-4830-ac32-5ea78462e8c4"))
         radiation.setPcpPhone(o.getValueText());
       if (o.getConcept().getUuid().equals("47d58999-d3b5-4869-a52e-841e2e6bdbb3"))
         radiation.setInstitutionName(o.getValueText());
       if (o.getConcept().getUuid().equals("bfa752d6-2037-465e-b0a2-c4c2d485ec32"))
         radiation.setInstitutionCity(o.getValueText());
       if (o.getConcept().getUuid().equals("34489100-487e-443a-bf27-1b6869fb9332"))
         radiation.setInstitutionState(o.getValueText());
     }
     radiation.setRadiationTypes(radiationTypes);
     radiationsList.add(radiation);
   }
   return radiationsList;
 }
Exemplo n.º 22
0
  /**
   * This is an equivalent to a copy constructor. Creates a new copy of the given <code>obsToCopy
   * </code> with a null obs id
   *
   * @param obsToCopy The Obs that is going to be copied
   * @return a new Obs object with all the same attributes as the given obs
   */
  public static Obs newInstance(Obs obsToCopy) {
    Obs newObs =
        new Obs(
            obsToCopy.getPerson(),
            obsToCopy.getConcept(),
            obsToCopy.getObsDatetime(),
            obsToCopy.getLocation());

    newObs.setObsGroup(obsToCopy.getObsGroup());
    newObs.setAccessionNumber(obsToCopy.getAccessionNumber());
    newObs.setValueCoded(obsToCopy.getValueCoded());
    newObs.setValueDrug(obsToCopy.getValueDrug());
    newObs.setValueGroupId(obsToCopy.getValueGroupId());
    newObs.setValueDatetime(obsToCopy.getValueDatetime());
    newObs.setValueNumeric(obsToCopy.getValueNumeric());
    newObs.setValueModifier(obsToCopy.getValueModifier());
    newObs.setValueText(obsToCopy.getValueText());
    newObs.setComment(obsToCopy.getComment());
    newObs.setOrder(obsToCopy.getOrder());
    newObs.setEncounter(obsToCopy.getEncounter());
    newObs.setDateStarted(obsToCopy.getDateStarted());
    newObs.setDateStopped(obsToCopy.getDateStopped());
    newObs.setCreator(obsToCopy.getCreator());
    newObs.setDateCreated(obsToCopy.getDateCreated());
    newObs.setVoided(obsToCopy.getVoided());
    newObs.setVoidedBy(obsToCopy.getVoidedBy());
    newObs.setDateVoided(obsToCopy.getDateVoided());
    newObs.setVoidReason(obsToCopy.getVoidReason());

    newObs.setValueComplex(obsToCopy.getValueComplex());
    newObs.setComplexData(obsToCopy.getComplexData());

    if (obsToCopy.getGroupMembers() != null)
      for (Obs member : obsToCopy.getGroupMembers()) {
        // if the obs hasn't been saved yet, no need to duplicate it
        if (member.getObsId() == null) newObs.addGroupMember(member);
        else newObs.addGroupMember(Obs.newInstance(member));
      }

    return newObs;
  }
 public static List<GeneralHistory> generateGeneralHistory(Patient patient) {
   List<Encounter> encounters =
       getEncountersByTreatment(patient, PatientPortalToolkitConstants.TREATMENTSUMMARY_ENCOUNTER);
   List<GeneralHistory> generalHistoryList = new ArrayList<GeneralHistory>();
   for (Encounter e : encounters) {
     GeneralHistory generalHistory = new GeneralHistory();
     generalHistory.setEncounterUuid(e.getUuid());
     Set<Obs> obsList = e.getObs();
     for (Obs o : obsList) {
       if (o.getConcept().getUuid().equals("efa3f9eb-ade4-4ddb-92c9-0fc1119d112d"))
         generalHistory.setCancerStage(o.getValueCoded().getName().getName());
       if (o.getConcept().getUuid().equals("cdf6d767-2aa3-40b6-ae78-0386eebe2411"))
         generalHistory.setCancerType(o.getValueCoded().getName().getName());
       if (o.getConcept().getUuid().equals("395878ae-5108-4aad-8ad8-9b88e812d278")) {
         if (o.getValueCoded().getUuid().equals("1065AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"))
           generalHistory.setHasGeneticOrPredisposingAbnormality(true);
         else generalHistory.setHasGeneticOrPredisposingAbnormality(false);
       }
       if (o.getConcept().getUuid().equals("8719adbe-0975-477f-a95f-2fae4d6cbdae"))
         generalHistory.setGeneticOrPredisposingAbnormality(o.getValueCoded().getName().getName());
       if (o.getConcept().getUuid().equals("654e32f0-8b57-4d1f-845e-500922e800f6"))
         generalHistory.setDiagnosisDate(o.getValueDate());
       // doctors name
       if (o.getConcept().getUuid().equals("c2cb2220-c07d-47c6-a4df-e5918aac3fc2"))
         generalHistory.setPcpName(o.getValueText());
       // doctors email
       if (o.getConcept().getUuid().equals("898a0028-8c65-4db9-a802-1577fce59864"))
         generalHistory.setPcpEmail(o.getValueText());
       // doctors phone
       if (o.getConcept().getUuid().equals("9285b227-4054-4830-ac32-5ea78462e8c4"))
         generalHistory.setPcpPhone(o.getValueText());
     }
     generalHistoryList.add(generalHistory);
   }
   return generalHistoryList;
 }
  @Test
  public void shouldCreateObservations() throws Exception {
    Date visitStartDate = getDateFromString("2014-06-22 00:00:00");
    Date encounterDate = getDateFromString("2014-06-23 00:00:00");
    Date obsDate = getDateFromString("2014-06-24 00:10:00");

    List<Document> documents = new ArrayList<>();
    documents.add(new Document("/radiology/fooo-bar.jpg", null, conceptUuid, null, obsDate, false));

    visitDocumentRequest =
        new VisitDocumentRequest(
            patientUUID,
            secondVisitUuid,
            visitTypeUUID,
            visitStartDate,
            null,
            firstEncounterTypeUUID,
            encounterDate,
            documents,
            firstProviderUuid,
            FIRST_LOCATION_UUID,
            null);

    visitDocumentService.upload(visitDocumentRequest);

    Context.flushSession();
    Context.clearSession();

    Encounter encounter = encounterService.getEncounterByUuid(firstEncounterUuid);

    Obs savedDoc = getSavedDocument(encounter.getAllObs(), conceptUuid);

    assertNotNull(savedDoc);
    assertThat(savedDoc.getConcept().getId(), is(222));
    assertThat(
        savedDoc.getGroupMembers().iterator().next().getValueText(), is("/radiology/fooo-bar.jpg"));
    assertEquals(FIRST_LOCATION_UUID, encounter.getLocation().getUuid());
  }
Exemplo n.º 25
0
 /**
  * Creates an OpenMRS Obs instance
  *
  * @param concept concept associated with the Obs
  * @param value value associated with the Obs
  * @param datetime date/time associated with the Obs (may be null)
  * @param accessionNumber accession number associatd with the Obs (may be null)
  * @return the created Obs instance
  */
 public static Obs createObs(
     Concept concept, Object value, Date datetime, String accessionNumber) {
   Obs obs = new Obs();
   obs.setConcept(concept);
   ConceptDatatype dt = obs.getConcept().getDatatype();
   if (dt.isNumeric()) {
     obs.setValueNumeric(Double.parseDouble(value.toString()));
   } else if (dt.isText()) {
     if (value instanceof Location) {
       obs.setValueText(((Location) value).getLocationId().toString());
     } else {
       obs.setValueText(value.toString());
     }
   } else if (dt.isCoded()) {
     if (value instanceof Concept) obs.setValueCoded((Concept) value);
     else obs.setValueCoded((Concept) convertToType(value.toString(), Concept.class));
   } else if (dt.isBoolean()) {
     boolean booleanValue =
         value != null && !Boolean.FALSE.equals(value) && !"false".equals(value);
     obs.setValueNumeric(booleanValue ? 1.0 : 0.0);
   } else if (dt.isDate()) {
     Date date = (Date) value;
     obs.setValueDatetime(date);
   } else if ("ZZ".equals(dt.getHl7Abbreviation())) {
     // don't set a value
   } else {
     throw new IllegalArgumentException(
         "concept datatype not yet implemented: "
             + dt.getName()
             + " with Hl7 Abbreviation: "
             + dt.getHl7Abbreviation());
   }
   if (datetime != null) obs.setObsDatetime(datetime);
   if (accessionNumber != null) obs.setAccessionNumber(accessionNumber);
   return obs;
 }
 @Override
 public Concept getConcept() {
   return obs.getConcept();
 }
Exemplo n.º 27
0
  /**
   * This method produces a model containing the following mappings:
   *
   * <pre>
   *     (always)
   *          (java.util.Date) now
   *          (String) size
   *          (Locale) locale
   *          (String) portletUUID // unique for each instance of any portlet
   *          (other parameters)
   *     (if there's currently an authenticated user)
   *          (User) authenticatedUser
   *     (if the request has a patientId attribute)
   *          (Integer) patientId
   *          (Patient) patient
   *          (List<Obs>) patientObs
   *          (List<Encounter>) patientEncounters
   *          (List<DrugOrder>) patientDrugOrders
   *          (List<DrugOrder>) currentDrugOrders
   *          (List<DrugOrder>) completedDrugOrders
   *          (Obs) patientWeight // most recent weight obs
   *          (Obs) patientHeight // most recent height obs
   *          (Double) patientBmi // BMI derived from most recent weight and most recent height
   *          (String) patientBmiAsString // BMI rounded to one decimal place, or "?" if unknown
   *          (Integer) personId
   *          (if the patient has any obs for the concept in the global property 'concept.reasonExitedCare')
   *              (Obs) patientReasonForExit
   *     (if the request has a personId or patientId attribute)
   *          (Person) person
   *          (List<Relationship>) personRelationships
   *          (Map<RelationshipType, List<Relationship>>) personRelationshipsByType
   *     (if the request has an encounterId attribute)
   *          (Integer) encounterId
   *          (Encounter) encounter
   *          (Set<Obs>) encounterObs
   *     (if the request has a userId attribute)
   *          (Integer) userId
   *          (User) user
   *     (if the request has a patientIds attribute, which should be a (String) comma-separated list of patientIds)
   *          (PatientSet) patientSet
   *          (String) patientIds
   *     (if the request has a conceptIds attribute, which should be a (String) commas-separated list of conceptIds)
   *          (Map<Integer, Concept>) conceptMap
   *          (Map<String, Concept>) conceptMapByStringIds
   * </pre>
   *
   * @should calculate bmi into patientBmiAsString
   * @should not fail with empty height and weight properties
   */
  @SuppressWarnings("unchecked")
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    AdministrationService as = Context.getAdministrationService();
    ConceptService cs = Context.getConceptService();

    // find the portlet that was identified in the openmrs:portlet taglib
    Object uri = request.getAttribute("javax.servlet.include.servlet_path");
    String portletPath = "";
    Map<String, Object> model = null;
    {
      HttpSession session = request.getSession();
      String uniqueRequestId = (String) request.getAttribute(WebConstants.INIT_REQ_UNIQUE_ID);
      String lastRequestId =
          (String) session.getAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID);
      if (uniqueRequestId.equals(lastRequestId)) {
        model =
            (Map<String, Object>) session.getAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL);

        // remove cached parameters
        List<String> parameterKeys = (List<String>) model.get("parameterKeys");
        for (String key : parameterKeys) {
          model.remove(key);
        }
      }
      if (model == null) {
        log.debug("creating new portlet model");
        model = new HashMap<String, Object>();
        session.setAttribute(WebConstants.OPENMRS_PORTLET_LAST_REQ_ID, uniqueRequestId);
        session.setAttribute(WebConstants.OPENMRS_PORTLET_CACHED_MODEL, model);
      }
    }

    if (uri != null) {
      long timeAtStart = System.currentTimeMillis();
      portletPath = uri.toString();

      // Allowable extensions are '' (no extension) and '.portlet'
      if (portletPath.endsWith("portlet")) portletPath = portletPath.replace(".portlet", "");
      else if (portletPath.endsWith("jsp"))
        throw new ServletException(
            "Illegal extension used for portlet: '.jsp'. Allowable extensions are '' (no extension) and '.portlet'");

      log.debug("Loading portlet: " + portletPath);

      String id = (String) request.getAttribute("org.openmrs.portlet.id");
      String size = (String) request.getAttribute("org.openmrs.portlet.size");
      Map<String, Object> params =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameters");
      Map<String, Object> moreParams =
          (Map<String, Object>) request.getAttribute("org.openmrs.portlet.parameterMap");

      model.put("now", new Date());
      model.put("id", id);
      model.put("size", size);
      model.put("locale", Context.getLocale());
      model.put("portletUUID", UUID.randomUUID().toString().replace("-", ""));
      List<String> parameterKeys = new ArrayList<String>(params.keySet());
      model.putAll(params);
      if (moreParams != null) {
        model.putAll(moreParams);
        parameterKeys.addAll(moreParams.keySet());
      }
      model.put("parameterKeys", parameterKeys); // so we can clean these up in the next request

      // if there's an authenticated user, put them, and their patient set, in the model
      if (Context.getAuthenticatedUser() != null) {
        model.put("authenticatedUser", Context.getAuthenticatedUser());
      }

      Integer personId = null;

      // if a patient id is available, put patient data documented above in the model
      Object o = request.getAttribute("org.openmrs.portlet.patientId");
      if (o != null) {
        String patientVariation = "";
        Integer patientId = (Integer) o;
        if (!model.containsKey("patient")) {
          // we can't continue if the user can't view patients
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENTS)) {
            Patient p = Context.getPatientService().getPatient(patientId);
            model.put("patient", p);

            // add encounters if this user can view them
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS))
              model.put(
                  "patientEncounters", Context.getEncounterService().getEncountersByPatient(p));

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS)) {
              List<Obs> patientObs = Context.getObsService().getObservationsByPerson(p);
              model.put("patientObs", patientObs);
              Obs latestWeight = null;
              Obs latestHeight = null;
              String bmiAsString = "?";
              try {
                String weightString = as.getGlobalProperty("concept.weight");
                ConceptNumeric weightConcept = null;
                if (StringUtils.hasLength(weightString))
                  weightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(weightString)).getConceptId());
                String heightString = as.getGlobalProperty("concept.height");
                ConceptNumeric heightConcept = null;
                if (StringUtils.hasLength(heightString))
                  heightConcept =
                      cs.getConceptNumeric(
                          cs.getConcept(Integer.valueOf(heightString)).getConceptId());
                for (Obs obs : patientObs) {
                  if (obs.getConcept().equals(weightConcept)) {
                    if (latestWeight == null
                        || obs.getObsDatetime().compareTo(latestWeight.getObsDatetime()) > 0)
                      latestWeight = obs;
                  } else if (obs.getConcept().equals(heightConcept)) {
                    if (latestHeight == null
                        || obs.getObsDatetime().compareTo(latestHeight.getObsDatetime()) > 0)
                      latestHeight = obs;
                  }
                }
                if (latestWeight != null) model.put("patientWeight", latestWeight);
                if (latestHeight != null) model.put("patientHeight", latestHeight);
                if (latestWeight != null && latestHeight != null) {
                  double weightInKg;
                  double heightInM;
                  if (weightConcept.getUnits().equals("kg"))
                    weightInKg = latestWeight.getValueNumeric();
                  else if (weightConcept.getUnits().equals("lb"))
                    weightInKg = latestWeight.getValueNumeric() * 0.45359237;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of weight concept: " + weightConcept.getUnits());
                  if (heightConcept.getUnits().equals("cm"))
                    heightInM = latestHeight.getValueNumeric() / 100;
                  else if (heightConcept.getUnits().equals("m"))
                    heightInM = latestHeight.getValueNumeric();
                  else if (heightConcept.getUnits().equals("in"))
                    heightInM = latestHeight.getValueNumeric() * 0.0254;
                  else
                    throw new IllegalArgumentException(
                        "Can't handle units of height concept: " + heightConcept.getUnits());
                  double bmi = weightInKg / (heightInM * heightInM);
                  model.put("patientBmi", bmi);
                  String temp = "" + bmi;
                  bmiAsString = temp.substring(0, temp.indexOf('.') + 2);
                }
              } catch (Exception ex) {
                if (latestWeight != null && latestHeight != null)
                  log.error(
                      "Failed to calculate BMI even though a weight and height were found", ex);
              }
              model.put("patientBmiAsString", bmiAsString);
            } else {
              model.put("patientObs", new HashSet<Obs>());
            }

            // information about whether or not the patient has exited care
            Obs reasonForExitObs = null;
            String reasonForExitConceptString = as.getGlobalProperty("concept.reasonExitedCare");
            if (StringUtils.hasLength(reasonForExitConceptString)) {
              Concept reasonForExitConcept = cs.getConcept(reasonForExitConceptString);
              if (reasonForExitConcept != null) {
                List<Obs> patientExitObs =
                    Context.getObsService()
                        .getObservationsByPersonAndConcept(p, reasonForExitConcept);
                if (patientExitObs != null) {
                  log.debug("Exit obs is size " + patientExitObs.size());
                  if (patientExitObs.size() == 1) {
                    reasonForExitObs = patientExitObs.iterator().next();
                    Concept exitReason = reasonForExitObs.getValueCoded();
                    Date exitDate = reasonForExitObs.getObsDatetime();
                    if (exitReason != null && exitDate != null) {
                      patientVariation = "Exited";
                    }
                  } else {
                    if (patientExitObs.size() == 0) {
                      log.debug("Patient has no reason for exit");
                    } else {
                      log.error("Too many reasons for exit - not putting data into model");
                    }
                  }
                }
              }
            }
            model.put("patientReasonForExit", reasonForExitObs);

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_ORDERS)) {
              List<DrugOrder> drugOrderList = Context.getOrderService().getDrugOrdersByPatient(p);
              model.put("patientDrugOrders", drugOrderList);
              List<DrugOrder> currentDrugOrders = new ArrayList<DrugOrder>();
              List<DrugOrder> discontinuedDrugOrders = new ArrayList<DrugOrder>();
              Date rightNow = new Date();
              for (Iterator<DrugOrder> iter = drugOrderList.iterator(); iter.hasNext(); ) {
                DrugOrder next = iter.next();
                if (next.isCurrent() || next.isFuture()) currentDrugOrders.add(next);
                if (next.isDiscontinued(rightNow)) discontinuedDrugOrders.add(next);
              }
              model.put("currentDrugOrders", currentDrugOrders);
              model.put("completedDrugOrders", discontinuedDrugOrders);

              List<RegimenSuggestion> standardRegimens =
                  Context.getOrderService().getStandardRegimens();
              if (standardRegimens != null) model.put("standardRegimens", standardRegimens);
            }

            if (Context.hasPrivilege(PrivilegeConstants.VIEW_PROGRAMS)
                && Context.hasPrivilege(PrivilegeConstants.VIEW_PATIENT_PROGRAMS)) {
              model.put(
                  "patientPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, null, null, null, false));
              model.put(
                  "patientCurrentPrograms",
                  Context.getProgramWorkflowService()
                      .getPatientPrograms(p, null, null, new Date(), new Date(), null, false));
            }

            model.put("patientId", patientId);
            if (p != null) {
              personId = p.getPatientId();
              model.put("personId", personId);
            }

            model.put("patientVariation", patientVariation);
          }
        }
      }

      // if a person id is available, put person and relationships in the model
      if (personId == null) {
        o = request.getAttribute("org.openmrs.portlet.personId");
        if (o != null) {
          personId = (Integer) o;
          model.put("personId", personId);
        }
      }
      if (personId != null) {
        if (!model.containsKey("person")) {
          Person p = (Person) model.get("patient");
          if (p == null) p = Context.getPersonService().getPerson(personId);
          model.put("person", p);

          if (Context.hasPrivilege(PrivilegeConstants.VIEW_RELATIONSHIPS)) {
            List<Relationship> relationships = new ArrayList<Relationship>();
            relationships.addAll(Context.getPersonService().getRelationshipsByPerson(p));
            Map<RelationshipType, List<Relationship>> relationshipsByType =
                new HashMap<RelationshipType, List<Relationship>>();
            for (Relationship rel : relationships) {
              List<Relationship> list = relationshipsByType.get(rel.getRelationshipType());
              if (list == null) {
                list = new ArrayList<Relationship>();
                relationshipsByType.put(rel.getRelationshipType(), list);
              }
              list.add(rel);
            }

            model.put("personRelationships", relationships);
            model.put("personRelationshipsByType", relationshipsByType);
          }
        }
      }

      // if an encounter id is available, put "encounter" and "encounterObs" in the model
      o = request.getAttribute("org.openmrs.portlet.encounterId");
      if (o != null && !model.containsKey("encounterId")) {
        if (!model.containsKey("encounter")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_ENCOUNTERS)) {
            Encounter e = Context.getEncounterService().getEncounter((Integer) o);
            model.put("encounter", e);
            if (Context.hasPrivilege(PrivilegeConstants.VIEW_OBS))
              model.put("encounterObs", e.getObs());
          }
          model.put("encounterId", (Integer) o);
        }
      }

      // if a user id is available, put "user" in the model
      o = request.getAttribute("org.openmrs.portlet.userId");
      if (o != null) {
        if (!model.containsKey("user")) {
          if (Context.hasPrivilege(PrivilegeConstants.VIEW_USERS)) {
            User u = Context.getUserService().getUser((Integer) o);
            model.put("user", u);
          }
          model.put("userId", (Integer) o);
        }
      }

      // if a list of patient ids is available, make a patientset out of it
      o = request.getAttribute("org.openmrs.portlet.patientIds");
      if (o != null && !"".equals(o) && !model.containsKey("patientIds")) {
        if (!model.containsKey("patientSet")) {
          Cohort ps = new Cohort((String) o);
          model.put("patientSet", ps);
          model.put("patientIds", (String) o);
        }
      }

      o = model.get("conceptIds");
      if (o != null && !"".equals(o)) {
        if (!model.containsKey("conceptMap")) {
          log.debug("Found conceptIds parameter: " + o);
          Map<Integer, Concept> concepts = new HashMap<Integer, Concept>();
          Map<String, Concept> conceptsByStringIds = new HashMap<String, Concept>();
          String conceptIds = (String) o;
          String[] ids = conceptIds.split(",");
          for (String cId : ids) {
            try {
              Integer i = Integer.valueOf(cId);
              Concept c = cs.getConcept(i);
              concepts.put(i, c);
              conceptsByStringIds.put(i.toString(), c);
            } catch (Exception ex) {
            }
          }
          model.put("conceptMap", concepts);
          model.put("conceptMapByStringIds", conceptsByStringIds);
        }
      }

      populateModel(request, model);
      log.debug(portletPath + " took " + (System.currentTimeMillis() - timeAtStart) + " ms");
    }

    return new ModelAndView(portletPath, "model", model);
  }
    /**
     *
     * 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;
    }
  /**
   * @see EligibleForArtTriggerCalculation#evaluate(java.util.Collection, java.util.Map,
   *     org.openmrs.calculation.patient.PatientCalculationContext)
   * @verifies calculate the obs which triggered a patient to become eligible for ART
   * @verifies return null for patients who have never been eligible for ART
   */
  @Test
  public void evaluate_shouldCalculateEligibilityTrigger() throws Exception {

    PatientService ps = Context.getPatientService();

    // Confirm patient #6 HIV+ when they're 1 year old and give them very low CD4 soon after
    TestUtils.saveObs(
        ps.getPatient(6),
        Dictionary.getConcept(Dictionary.DATE_OF_HIV_DIAGNOSIS),
        TestUtils.date(2008, 05, 27),
        TestUtils.date(2010, 1, 1));
    TestUtils.saveObs(
        ps.getPatient(6),
        Dictionary.getConcept(Dictionary.CD4_COUNT),
        300.0,
        TestUtils.date(2009, 1, 1));

    // Give patient #7 low CD4 when they're 3 years old and very low CD4 after
    TestUtils.saveObs(
        ps.getPatient(7),
        Dictionary.getConcept(Dictionary.CD4_COUNT),
        900.0,
        TestUtils.date(1979, 8, 25));
    TestUtils.saveObs(
        ps.getPatient(7),
        Dictionary.getConcept(Dictionary.CD4_COUNT),
        300.0,
        TestUtils.date(2009, 1, 1));

    // Give patient #8 WHO stage of 3
    TestUtils.saveObs(
        ps.getPatient(8),
        Dictionary.getConcept(Dictionary.CURRENT_WHO_STAGE),
        Dictionary.getConcept(Dictionary.WHO_STAGE_3_PEDS),
        TestUtils.date(2009, 1, 1));

    Context.flushSession();

    List<Integer> cohort = Arrays.asList(6, 7, 8, 999);

    CalculationResultMap resultMap =
        new EligibleForArtTriggerCalculation()
            .evaluate(
                cohort,
                null,
                Context.getService(PatientCalculationService.class).createCalculationContext());

    Obs patient6Trigger = (Obs) resultMap.get(6).getValue(); // Eligible through HIV confirmation
    Assert.assertEquals(Dictionary.DATE_OF_HIV_DIAGNOSIS, patient6Trigger.getConcept().getUuid());
    Assert.assertEquals(TestUtils.date(2008, 05, 27), patient6Trigger.getValueDate());

    Obs patient7Trigger = (Obs) resultMap.get(7).getValue(); // Eligible through CD4 count
    Assert.assertEquals(Dictionary.CD4_COUNT, patient7Trigger.getConcept().getUuid());
    Assert.assertEquals(TestUtils.date(1979, 8, 25), patient7Trigger.getObsDatetime());

    Obs patient8Trigger = (Obs) resultMap.get(8).getValue(); // Eligible through WHO stage
    Assert.assertEquals(Dictionary.CURRENT_WHO_STAGE, patient8Trigger.getConcept().getUuid());
    Assert.assertEquals(TestUtils.date(2009, 1, 1), patient8Trigger.getObsDatetime());

    Assert.assertNull(resultMap.get(999)); // Was never eligible for ART
  }
 private CodeableConceptDt buildCode(Obs observation) {
   if (null == observation.getConcept()) {
     return null;
   }
   return codeableConceptService.addTRCodingOrDisplay(observation.getConcept());
 }