@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;
  }
  /** @see org.openmrs.api.db.ObsDAO#saveObs(org.openmrs.Obs) */
  public Obs saveObs(Obs obs) throws DAOException {
    if (obs.hasGroupMembers() && obs.getObsId() != null) {
      // hibernate has a problem updating child collections
      // if the parent object was already saved so we do it
      // explicitly here
      for (Obs member : obs.getGroupMembers()) if (member.getObsId() == null) saveObs(member);
    }

    sessionFactory.getCurrentSession().saveOrUpdate(obs);

    return obs;
  }
Example #3
0
  /**
   * Compares two Obs for similarity. The comparison is done on obsId of both this and the given
   * <code>obs</code> object. If either has a null obsId, then they are not equal
   *
   * @param obj
   * @return boolean True if the obsIds match, false otherwise or if either obsId is null.
   */
  public boolean equals(Object obj) {
    if (obj instanceof Obs) {
      Obs o = (Obs) obj;
      if (this.getObsId() != null && o.getObsId() != null)
        return (this.getObsId().equals(o.getObsId()));
      /*
       * return (this.getConcept().equals(o.getConcept()) &&
       * this.getPatient().equals(o.getPatient()) &&
       * this.getEncounter().equals(o.getEncounter()) &&
       * this.getLocation().equals(o.getLocation()));
       */
    }

    // if the obsIds don't match, its possible that they are the same
    // exact object. Check that now on the way out.
    return this == obj;
  }
  @Test
  public void testParsingDispositionWithTransferLocation() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Transfer")
            .get();
    when(emrConceptService.getConcept("test:transfer")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.transfer",
                "Transfer",
                "test:transfer",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Obs transferLocationObs = new Obs();
    transferLocationObs.setObsId(100);
    transferLocationObs.setConcept(dispositionDescriptor.getInternalTransferLocationConcept());
    transferLocationObs.setValueText("3");
    dispositionObs.addGroupMember(transferLocationObs);

    Location transferLocation = new Location();
    transferLocation.setName("Outpatient clinic");
    when(locationService.getLocation(3)).thenReturn(transferLocation);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedTransferLocationObject =
        SimpleObject.create("obsId", transferLocationObs.getObsId());
    expectedTransferLocationObject.put("question", "Transfer location");
    expectedTransferLocationObject.put("answer", "Outpatient clinic");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedTransferLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Transfer"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  @Test
  public void testParsingDispositionWithDateOfDeath() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Death")
            .get();
    when(emrConceptService.getConcept("test:death")).thenReturn(admit);

    Obs dispositionObs =
        dispositionDescriptor.buildObsGroup(
            new Disposition(
                "emrapi.death",
                "Death",
                "test:death",
                Collections.<String>emptyList(),
                Collections.<DispositionObs>emptyList()),
            emrConceptService);

    Date dateOfDeath = new DateTime(2012, 2, 20, 10, 10, 10).toDate();
    Obs dateOfDeathObs = new Obs();
    dateOfDeathObs.setObsId(100);
    dateOfDeathObs.setConcept(dispositionDescriptor.getDateOfDeathConcept());
    dateOfDeathObs.setValueDate(dateOfDeath);
    dispositionObs.addGroupMember(dateOfDeathObs);

    encounter.addObs(doNotGoToServiceToFormatMembers(dispositionObs));
    ParsedObs parsed = parser.parseObservations(Locale.ENGLISH);

    SimpleObject expectedAdmissionLocationObject =
        SimpleObject.create("obsId", dateOfDeathObs.getObsId());
    expectedAdmissionLocationObject.put("question", "Date of death");
    expectedAdmissionLocationObject.put("answer", "20 Feb 2012 10:10 AM");

    List<SimpleObject> expectedAdditionalObsList = new ArrayList<SimpleObject>();
    expectedAdditionalObsList.add(expectedAdmissionLocationObject);

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Death"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
Example #6
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;
  }
    /**
     *
     * 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;
    }
 @Override
 public Integer getObsId() {
   return obs.getObsId();
 }
  /**
   * Save obs corresponding to given http servlet request, http servlet response, radiologyOrder,
   * obs, obs, obsErrors
   *
   * @param request the http servlet request with all parameters
   * @param response the http servlet response
   * @param radiologyOrder the corresponding radiology order
   * @param obs the obs
   * @param obsErrors the result of the parameter binding
   * @return ModelAndView populated with obs matching the given criteria
   * @should save obs with given parameters
   * @should return populated model and view if binding errors occur
   * @should return populated model and view if edit reason is empty and obs id not null
   * @should return populated model and view if edit reason is null and obs id not null
   * @should return redirecting model and view for not authenticated user
   * @should edit obs with edit reason and complex concept
   * @should edit obs with edit reason, complex concept and request which is an instance of
   *     multihttpserveletrequest
   * @should edit obs with edit reason concept not complex and request which is an instance of
   *     multihttpserveletrequest
   * @should populate model and view with obs occuring thrown APIException
   */
  @RequestMapping(
      value = "/module/radiology/radiologyObs.form",
      method = RequestMethod.POST,
      params = "saveObs")
  ModelAndView saveObs(
      HttpServletRequest request,
      HttpServletResponse response,
      @RequestParam(value = "editReason", required = false) String editReason,
      @RequestParam(value = "orderId", required = true) RadiologyOrder radiologyOrder,
      @ModelAttribute("obs") Obs obs,
      BindingResult obsErrors) {

    HttpSession httpSession = request.getSession();

    new ObsValidator().validate(obs, obsErrors);

    if (obsErrors.hasErrors()) {
      return populateModelAndView(radiologyOrder, obs);
    }
    if (Context.isAuthenticated()) {

      try {
        // if the user is just editing the obs
        if (obs.getObsId() != null && (editReason == null || editReason.isEmpty())) {
          obsErrors.reject("editReason", "Obs.edit.reason.empty");

          return populateModelAndView(radiologyOrder, obs);
        }

        if (obs.getConcept().isComplex()) {
          if (request instanceof MultipartHttpServletRequest) {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            MultipartFile complexDataFile = multipartRequest.getFile("complexDataFile");
            if (complexDataFile != null && !complexDataFile.isEmpty()) {
              InputStream complexDataInputStream = complexDataFile.getInputStream();

              ComplexData complexData =
                  new ComplexData(complexDataFile.getOriginalFilename(), complexDataInputStream);

              obs.setComplexData(complexData);

              // the handler on the obs.concept is called
              // with
              // the given complex data
              obsService.saveObs(obs, editReason);
              updateReadingPhysician(radiologyOrder.getStudy());
              complexDataInputStream.close();
            }
          }
        } else {
          obsService.saveObs(obs, editReason);
          updateReadingPhysician(radiologyOrder.getStudy());
        }
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Obs.saved");
      } catch (APIException e) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        return populateModelAndView(radiologyOrder, obs);
      } catch (IOException e) {
        return populateModelAndView(radiologyOrder, obs);
      }
    }
    return new ModelAndView(
        "redirect:"
            + RADIOLOGY_OBS_FORM_URL
            + "orderId="
            + obs.getOrder().getId()
            + "&obsId="
            + obs.getId());
  }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
   *     java.lang.Object, org.springframework.validation.Errors)
   */
  @Override
  protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors error)
      throws Exception {

    Encounter encounter = (Encounter) obj;

    // the generic returned key-value pair mapping
    Map<String, Object> map = new HashMap<String, Object>();

    // obsIds of obs that were edited
    List<Integer> editedObs = new Vector<Integer>();

    // the map returned to the form
    // This is a mapping between the formfield and a list of the Obs/ObsGroup in that field
    // This mapping is sorted according to the comparator in FormField.java
    SortedMap<FormField, List<Obs>> obsMapToReturn = null;
    String sortType =
        Context.getAdministrationService()
            .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_ENCOUNTER_FORM_OBS_SORT_ORDER);
    if ("weight".equals(sortType)) {
      obsMapToReturn = new TreeMap<FormField, List<Obs>>(); // use FormField.compareTo
    } else {
      obsMapToReturn =
          new TreeMap<FormField, List<Obs>>(
              new NumberingFormFieldComparator()); // use custom comparator
    }

    // this maps the obs to form field objects for non top-level obs
    // it is keyed on obs so that when looping over an exploded obsGroup
    // the formfield can be fetched easily (in order to show the field numbers etc)
    Map<Obs, FormField> otherFormFields = new HashMap<Obs, FormField>();

    if (Context.isAuthenticated()) {
      EncounterService es = Context.getEncounterService();
      FormService fs = Context.getFormService();

      // used to restrict the form field lookup
      Form form = encounter.getForm();

      List<EncounterType> encTypes = es.getAllEncounterTypes();
      // Non-retired types first
      Collections.sort(encTypes, new MetadataComparator(Context.getLocale()));
      map.put("encounterTypes", encTypes);

      map.put("encounterRoles", es.getAllEncounterRoles(false));
      map.put("forms", Context.getFormService().getAllForms());
      // loop over the encounter's observations to find the edited obs
      for (Obs o : encounter.getObsAtTopLevel(true)) {

        // only edited obs has previous version
        if (o.hasPreviousVersion()) {
          editedObs.add(o.getObsId());
        }

        // get the formfield for this obs
        FormField ff = fs.getFormField(form, o.getConcept(), obsMapToReturn.keySet(), false);
        if (ff == null) {
          ff = new FormField();
        }

        // we only put the top-level obs in the obsMap.  Those would
        // be the obs that don't have an obs grouper
        if (o.getObsGroup() == null) {
          // populate the obs map with this formfield and obs
          List<Obs> list = obsMapToReturn.get(ff);
          if (list == null) {
            list = new Vector<Obs>();
            obsMapToReturn.put(ff, list);
          }
          list.add(o);
        } else {
          // this is not a top-level obs, just put the formField
          // in a separate list and be done with it
          otherFormFields.put(o, ff);
        }
      }
    }

    if (log.isDebugEnabled()) {
      log.debug("setting obsMap in page context (size: " + obsMapToReturn.size() + ")");
    }
    map.put("obsMap", obsMapToReturn);

    map.put("otherFormFields", otherFormFields);

    map.put("locale", Context.getLocale());
    map.put("editedObs", editedObs);
    if (encounter.getPatient() != null) {
      map.put(
          "patientVisits", Context.getVisitService().getVisitsByPatient(encounter.getPatient()));
    }

    return map;
  }
Example #11
0
  /**
   * @return Returns the obsId of the parent obs group
   * @deprecated The {@link #getObsGroup()} method should be used
   * @see #getObsGroup()
   */
  public Integer getObsGroupId() {
    if (getObsGroup() == null) return null;

    return obsGroup.getObsId();
  }