private void addToObsGroup(Obs obsGroup, Obs member) {
   member.setPerson(obsGroup.getPerson());
   member.setObsDatetime(obsGroup.getObsDatetime());
   member.setLocation(obsGroup.getLocation());
   member.setEncounter(obsGroup.getEncounter());
   obsGroup.addGroupMember(member);
 }
  /** @see Encounter#addObs(Obs) */
  @Test
  @Verifies(
      value = "should add encounter attrs to obs if attributes are null",
      method = "addObs(Obs)")
  public void addObs_shouldAddEncounterAttrsToObsIfAttributesAreNull() throws Exception {
    /// an encounter that will hav the date/location/patient on it
    Encounter encounter = new Encounter();

    Date date = new Date();
    encounter.setEncounterDatetime(date);

    Location location = new Location(1);
    encounter.setLocation(location);

    Patient patient = new Patient(1);
    encounter.setPatient(patient);

    // add an obs that doesn't have date/location/patient set on it.
    Obs obs = new Obs(123);
    encounter.addObs(obs);

    // make sure it was added
    assertEquals(1, encounter.getAllObs(true).size());

    // check the values of the obs attrs to see if they were added
    assertTrue(obs.getObsDatetime().equals(date));
    assertTrue(obs.getLocation().equals(location));
    assertTrue(obs.getPerson().equals(patient));
  }
 public ObsBuilder addMember(Concept question, String valueText) {
   Obs child = new Obs();
   child.setPerson(obs.getPerson());
   child.setObsDatetime(obs.getObsDatetime());
   child.setConcept(question);
   child.setValueText(valueText);
   obs.addGroupMember(child);
   return this;
 }
  public QueueItem saveQueueItem(QueueItem queueItem) {
    log.debug("saveQueueItem(). Entering");
    boolean isNew = false;
    Date newDate = queueItem.getEncounter().getEncounterDatetime();
    log.debug("Encounter date: " + newDate);
    Date originalDate = null;

    if (queueItem.getQueueItemId() == null) {
      isNew = true;
      log.debug("Got a  new queue item");
    }

    // Not new we update some of the Encounter info
    if (!isNew) {
      log.info("Updating previously queued encounter!");
      Encounter encounter = queueItem.getEncounter();
      Patient p = encounter.getPatient();
      originalDate = encounter.getEncounterDatetime();
      if (OpenmrsUtil.compare(originalDate, newDate) != 0) {

        // if the obs datetime is the same as the
        // original encounter datetime, fix it
        if (OpenmrsUtil.compare(queueItem.getDateCreated(), originalDate) == 0) {
          encounter.setEncounterDatetime(newDate);
        }
      }

      // if the Person in the encounter doesn't match the Patient in the ,
      // fix it
      if (!encounter.getPatient().getPersonId().equals(p.getPatientId())) {
        encounter.setPatient(p);
      }

      for (Obs obs : encounter.getAllObs(true)) {
        // if the date was changed
        if (OpenmrsUtil.compare(originalDate, newDate) != 0) {

          // if the obs datetime is the same as the
          // original encounter datetime, fix it
          if (OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0) {
            obs.setObsDatetime(newDate);
          }
        }

        // if the Person in the obs doesn't match the Patient in the
        // encounter, fix it
        if (!obs.getPerson().getPersonId().equals(p.getPatientId())) {
          obs.setPerson(p);
        }
      }
    }
    log.debug("Saving queu item.");
    dao.saveQueueItem(queueItem);
    return queueItem;
  }
  /** @see Encounter#addObs(Obs) */
  @Test
  @Verifies(
      value = "should add encounter attrs to obs if attributes are null",
      method = "addObs(Obs)")
  public void addObs_shouldAddEncounterAttrsToObsGroupMembersIfAttributesAreNull()
      throws Exception {
    /// an encounter that will hav the date/location/patient on it
    Encounter encounter = new Encounter();

    Date date = new Date();
    encounter.setEncounterDatetime(date);

    Location location = new Location(1);
    encounter.setLocation(location);

    Patient patient = new Patient(1);
    encounter.setPatient(patient);

    // add an obs that doesn't have date/location/patient set on it.
    Obs obs = new Obs(123);
    Obs childObs = new Obs(456);
    obs.addGroupMember(childObs);

    // check for infinite recursion
    // childObs-->childObs2   and childObs2-->childObs
    Obs childObs2 = new Obs(456);
    childObs.addGroupMember(childObs2);
    childObs2.addGroupMember(childObs);

    assertTrue(obs.getGroupMembers() != null && obs.getGroupMembers().size() == 1);

    encounter.addObs(obs);

    // check the values of the obs attrs to see if they were added
    assertTrue(childObs.getObsDatetime().equals(date));
    assertTrue(childObs.getLocation().equals(location));
    assertTrue(childObs.getPerson().equals(patient));
    assertTrue(childObs2.getObsDatetime().equals(date));
    assertTrue(childObs2.getLocation().equals(location));
    assertTrue(childObs2.getPerson().equals(patient));
  }
  @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());
  }
  /** @see RadiologyObsFormController#getNewObs(Order) */
  @Test
  @Verifies(
      value = "should populate model and view with new obs given a valid order",
      method = "getNewObs(Order)")
  public void getNewObs_shouldPopulateModelAndViewWithNewObsGivenAValidOrder() throws Exception {

    ModelAndView modelAndView = radiologyObsFormController.getNewObs(mockRadiologyOrder);

    assertNotNull(modelAndView);
    assertThat(modelAndView.getViewName(), is("module/radiology/radiologyObsForm"));

    assertThat(modelAndView.getModelMap(), hasKey("obs"));
    Obs obs = (Obs) modelAndView.getModelMap().get("obs");

    assertNotNull(obs.getOrder());
    assertThat((RadiologyOrder) obs.getOrder(), is(mockRadiologyOrder));
    assertThat(obs.getPerson(), is((Person) mockRadiologyOrder.getPatient()));
  }
  /** @see RadiologyObsFormController#populateModelAndView(RadiologyOrder, Obs) */
  @Test
  @Verifies(
      value =
          "should populate the model and view for given radiology order  with completed study and obs",
      method = "populateModelAndView(RadiologyOrder, Obs)")
  public void
      populateModelAndView_ShouldPopulateModelAndViewWithObsForGivenRadiologyOrderWithCompletedStudyAndObs()
          throws Exception {

    mockStudy.setPerformedStatus(PerformedProcedureStepStatus.COMPLETED);

    Method populateModelAndViewMethod =
        radiologyObsFormController
            .getClass()
            .getDeclaredMethod(
                "populateModelAndView",
                new Class[] {
                  org.openmrs.module.radiology.RadiologyOrder.class, org.openmrs.Obs.class
                });
    populateModelAndViewMethod.setAccessible(true);

    ModelAndView modelAndView =
        (ModelAndView)
            populateModelAndViewMethod.invoke(
                radiologyObsFormController, new Object[] {mockRadiologyOrder, mockObs});

    assertThat(mockObs.getPerson(), is((Person) mockRadiologyOrder.getPatient()));

    assertThat(modelAndView.getModelMap(), hasKey("obs"));
    Obs obs = (Obs) modelAndView.getModelMap().get("obs");
    assertThat(obs, is(mockObs));

    assertThat(modelAndView.getModelMap(), hasKey("studyUID"));
    String studyUID = (String) modelAndView.getModelMap().get("studyUID");
    assertNotNull(studyUID);
    assertThat(studyUID, is(mockStudy.getStudyInstanceUid()));

    assertThat(modelAndView.getModelMap(), hasKey("previousObs"));
    List<Obs> previousObs = (List<Obs>) modelAndView.getModelMap().get("previousObs");
    assertNotNull(previousObs);
    assertThat(previousObs, is(radiologyService.getObsByOrderId(mockRadiologyOrder.getId())));

    assertThat(modelAndView.getModelMap(), hasKey("dicomViewerUrl"));
  }
Esempio n. 9
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;
  }
  @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());
  }
  /**
   * gets patients with more value on a given concept
   *
   * @param concept
   * @param value
   * @return patients
   */
  public List<Patient> getPatientsWithMoreValueOnConcept(Concept concept, double value) {
    List<Patient> allPatients = new ArrayList<Patient>();
    List<Patient> patients = new ArrayList<Patient>();
    List<Person> persons = new ArrayList<Person>();
    List<Obs> observers = new ArrayList<Obs>();
    allPatients = getAllPatients();
    observers = getObservationsByPersonAndConcept(null, concept);

    for (Obs obs : observers) {
      if (value <= obs.getValueNumeric()) {
        // log.info("XXXXXXXXXXXXXXXXXXX value "+value+"BBBBBBBBBBBBBBBBBBBBB obs.getValueNumeric()
        // "+obs.getValueNumeric());
        persons.add(obs.getPerson());
      }
    }
    for (Patient patient : allPatients) {

      if (persons.contains(patient)) {
        patients.add(patient);
      }
    }
    return patients;
  }
  /** @see org.openmrs.api.EncounterService#saveEncounter(org.openmrs.Encounter) */
  public Encounter saveEncounter(Encounter encounter) throws APIException {

    // if authenticated user is not supposed to edit encounter of certain type
    if (!canEditEncounter(encounter, null)) {
      throw new APIException(
          "Encounter.error.privilege.required.edit",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    // If new encounter, try to assign a visit using the registered visit assignment handler.
    if (encounter.getEncounterId() == null) {

      // Am using Context.getEncounterService().getActiveEncounterVisitHandler() instead of just
      // getActiveEncounterVisitHandler() for modules which may want to AOP around this call.
      EncounterVisitHandler encounterVisitHandler =
          Context.getEncounterService().getActiveEncounterVisitHandler();
      if (encounterVisitHandler != null) {
        encounterVisitHandler.beforeCreateEncounter(encounter);

        // If we have been assigned a new visit, persist it.
        if (encounter.getVisit() != null && encounter.getVisit().getVisitId() == null) {
          Context.getVisitService().saveVisit(encounter.getVisit());
        }
      }
    }

    boolean isNewEncounter = false;
    Date newDate = encounter.getEncounterDatetime();
    Date originalDate = null;
    Location newLocation = encounter.getLocation();
    Location originalLocation = null;
    // check permissions
    if (encounter.getEncounterId() == null) {
      isNewEncounter = true;
      Context.requirePrivilege(PrivilegeConstants.ADD_ENCOUNTERS);
    } else {
      Context.requirePrivilege(PrivilegeConstants.EDIT_ENCOUNTERS);
    }

    // This must be done after setting dateCreated etc on the obs because
    // of the way the ORM tools flush things and check for nullity
    // This also must be done before the save encounter so we can use the
    // orig date
    // after the save
    Patient p = encounter.getPatient();

    if (!isNewEncounter) {
      // fetch the datetime from the database prior to saving for this
      // encounter
      // to see if it has changed and change all obs after saving if so
      originalDate = dao.getSavedEncounterDatetime(encounter);
      if (encounter.getLocation() != null) {
        originalLocation = dao.getSavedEncounterLocation(encounter);
      }
      // Our data model duplicates the patient column to allow for
      // observations to
      // not have to look up the parent Encounter to find the patient
      // Therefore, encounter.patient must always equal
      // encounter.observations[0-n].patient

      // If we are changing encounter.encounterDatetime, then we need to
      // also apply that
      // to Obs that inherited their obsDatetime from the encounter in the
      // first place

      for (Obs obs : encounter.getAllObs(true)) {
        // if the date was changed
        if (OpenmrsUtil.compare(originalDate, newDate) != 0
            && OpenmrsUtil.compare(obs.getObsDatetime(), originalDate) == 0) {

          // if the obs datetime is the same as the
          // original encounter datetime, fix it
          obs.setObsDatetime(newDate);
        }

        if (!OpenmrsUtil.nullSafeEquals(newLocation, originalLocation)
            && obs.getLocation().equals(originalLocation)) {
          obs.setLocation(newLocation);
        }

        // if the Person in the obs doesn't match the Patient in the
        // encounter, fix it
        if (!obs.getPerson().getPersonId().equals(p.getPatientId())) {
          obs.setPerson(p);
        }
      }
    }
    // same goes for Orders
    for (Order o : encounter.getOrders()) {
      if (!p.equals(o.getPatient())) {
        o.setPatient(p);
      }
    }

    // do the actual saving to the database
    dao.saveEncounter(encounter);

    // save the new orders
    for (Order o : encounter.getOrders()) {
      if (o.getOrderId() == null) {
        Context.getOrderService().saveOrder(o, null);
      }
    }
    return encounter;
  }