/**
  * @see
  *     org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest)
  */
 @Override
 protected Map<String, Object> referenceData(HttpServletRequest request) throws Exception {
   Map<String, Object> ret = new HashMap<String, Object>();
   List<LocationTag> tags = Context.getLocationService().getAllLocationTags();
   Collections.sort(tags, new MetadataComparator(Context.getLocale()));
   ret.put("locationTags", tags);
   ret.put("attributeTypes", Context.getLocationService().getAllLocationAttributeTypes());
   return ret;
 }
  /**
   * The onSubmit function receives the form/command object that was modified by the input form and
   * saves it to the db
   *
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
   *     javax.servlet.http.HttpServletResponse, java.lang.Object,
   *     org.springframework.validation.BindException)
   * @should retire location
   * @should not retire location if reason is empty
   */
  protected ModelAndView onSubmit(
      HttpServletRequest request, HttpServletResponse response, Object obj, BindException errors)
      throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();
    if (Context.isAuthenticated()) {
      try {
        Location location = (Location) obj;
        WebAttributeUtil.handleSubmittedAttributesForType(
            location,
            errors,
            LocationAttribute.class,
            request,
            Context.getLocationService().getAllLocationAttributeTypes());

        if (errors.hasErrors()) {
          return showForm(request, response, errors);
        }

        LocationService locationService = Context.getLocationService();

        // if the user was editing the location
        if (request.getParameter("saveLocation") != null) {
          locationService.saveLocation(location);
          httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Location.saved");
        }
        // the 'retire this location' button was clicked
        else if (request.getParameter("retireLocation") != null) {
          locationService.retireLocation(location, location.getRetireReason());
          httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Location.retired");
        }
        // the 'unretire this location' button was clicked
        else if (request.getParameter("unretireLocation") != null) {
          locationService.unretireLocation(location);
          httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Location.unretired");
        }
      } catch (APIException e) {
        log.error("Error while saving location: " + obj, e);
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, e.getMessage());
        return showForm(request, response, errors);
      }

      view = getSuccessView();
    }

    return new ModelAndView(new RedirectView(view));
  }
 /**
  * Gets the specified location attribute type
  *
  * @param uuid the uuid
  * @return the location attribute type
  */
 public static LocationAttributeType getLocationAttributeType(String uuid) {
   LocationAttributeType ret = Context.getLocationService().getLocationAttributeTypeByUuid(uuid);
   if (ret == null) {
     throw new IllegalArgumentException("No such location attribute type with identifier " + uuid);
   }
   return ret;
 }
Exemplo n.º 4
0
  /**
   * Creates a non-persistent "Fake" Person (used when previewing or validating an HTML Form)
   *
   * @return the "fake" person
   */
  public static Patient getFakePerson() {
    Patient demo = new Patient();
    demo.addName(new PersonName("Demo", "The", "Person"));
    Location l = Context.getLocationService().getAllLocations().iterator().next();
    for (PatientIdentifierType pit : Context.getPatientService().getAllPatientIdentifierTypes()) {
      if (StringUtils.isEmpty(pit.getValidator())) {
        demo.addIdentifier(new PatientIdentifier("Testing" + pit.getName() + "123", pit, l));
      }
    }
    demo.setGender("F");
    demo.setUuid("testing-html-form-entry");
    {
      Calendar cal = Calendar.getInstance();
      cal.add(Calendar.YEAR, -31);
      demo.setBirthdate(cal.getTime());
    }

    for (PersonAttributeType type : Context.getPersonService().getAllPersonAttributeTypes()) {
      if (type.getFormat().equals("java.lang.String")) {
        demo.addAttribute(new PersonAttribute(type, "Test " + type.getName() + " Attribute"));
      }
    }
    PersonAddress addr = new PersonAddress();
    addr.setCityVillage("Rwinkwavu");
    addr.setCountyDistrict("Kayonza District");
    addr.setStateProvince("Eastern Province");
    addr.setCountry("Rwanda");
    demo.addAddress(addr);
    return demo;
  }
 /**
  * Gets the specified location
  *
  * @param uuid the identifier
  * @return the location
  */
 public static Location getLocation(String uuid) {
   Location ret = Context.getLocationService().getLocationByUuid(uuid);
   if (ret == null) {
     throw new IllegalArgumentException("No such location with identifier " + uuid);
   }
   return ret;
 }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldReturnEncounterVoided() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));

    // add a bunch of obs...
    TestUtil.addObs(e, 2474, Context.getConceptService().getConcept(656), date); // matches

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

    // this is going to test out the voided state of the obs in the encounter after processing:
    Assert.assertTrue(e.isVoided());
  }
  public void saveAndTransferFileComplexObs() {

    try {
      List<Encounter> encounters =
          Context.getEncounterService().getEncounters(null, null, null, null, null, null, true);
      Encounter lastEncounter = encounters.get(encounters.size() - 1);

      Person patient = lastEncounter.getPatient();
      ConceptComplex conceptComplex = Context.getConceptService().getConceptComplex(17);
      Location location = Context.getLocationService().getDefaultLocation();
      Obs obs = new Obs(patient, conceptComplex, new Date(), location);

      String mergedUrl = tempFile.getCanonicalPath();
      InputStream out1 = new FileInputStream(new File(mergedUrl));

      ComplexData complexData = new ComplexData(tempFile.getName(), out1);
      obs.setComplexData(complexData);
      obs.setEncounter(lastEncounter);

      Context.getObsService().saveObs(obs, null);
      tempFile.delete();

    } catch (Exception e) {
      log.error(e);
    }
  }
 /**
  * @verifies throw IllegalArgumentException if the name is longer than 255 characters
  * @see ICashPointService#getCashPointsByLocationAndName(org.openmrs.Location, String, boolean)
  */
 @Test(expected = IllegalArgumentException.class)
 public void
     getCashPointsByLocationAndName_shouldThrowIllegalArgumentExceptionIfTheNameIsLongerThan255Characters()
         throws Exception {
   service.getCashPointsByLocationAndName(
       Context.getLocationService().getLocation(1), StringUtils.repeat("A", 256), false);
 }
  /**
   * @see LabCatalogService#getLabTestPanelsByLocation(Location,Boolean,Integer,Integer)
   * @verifies return LabTestPanel by Location location, Boolean includeVoided, Integer start,
   *     Integer length
   */
  @Test
  public void
      getLabTestPanelsByLocation_shouldReturnLabTestPanelByLocationLocationBooleanIncludeVoidedIntegerStartIntegerLength()
          throws Exception {

    Location jsslab = Context.getLocationService().getLocation(33333005);
    Location extlab = Context.getLocationService().getLocation(33333011);

    List<LabTestPanel> testPanels =
        Context.getService(LabCatalogService.class).getLabTestPanelsByLocation(jsslab, true, 0, -1);
    Assert.assertEquals(3, testPanels.size());

    testPanels =
        Context.getService(LabCatalogService.class).getLabTestPanelsByLocation(extlab, true, 0, -1);
    Assert.assertEquals(2, testPanels.size());
  }
  /**
   * @verifies return an empty list if the location has no cashpoints
   * @see ICashPointService#getCashPointsByLocation(org.openmrs.Location, boolean)
   */
  @Test
  public void getCashPointsByLocation_shouldReturnAnEmptyListIfTheLocationHasNoCashpoints()
      throws Exception {
    Location location = Context.getLocationService().getLocation(4);

    List<CashPoint> results = service.getCashPointsByLocation(location, false);
    Assert.assertNotNull(results);
    Assert.assertEquals(0, results.size());
  }
 /**
  * Auto generated method comment
  *
  * @param locationId
  * @return
  */
 public static String getLocationName(Integer locationId) {
   try {
     if (null == locationId) return "";
     Location loc = Context.getLocationService().getLocation(locationId);
     return (loc != null) ? loc.getDisplayString() : "";
   } catch (Exception e) {
     log.info(e.getMessage());
     return "";
   }
 }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldHandleDrugOrderCorrectly() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 1, 5000, date); // a matching obs

    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

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

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, "test void reason");

    // this is going to test out the voided state of the obs in the encounter after processing:
    // order was matched, so order was voided, and because that's the only thing in the encounter,
    // encounter was voided too.
    Assert.assertTrue(e.isVoided());
    Assert.assertTrue(e.getVoidReason().equals("test void reason"));
    for (Order o : e.getOrders()) {
      Assert.assertTrue(o.isVoided());
      Assert.assertTrue(o.getVoidReason().equals("test void reason"));
    }
    for (Obs o : e.getAllObs(true)) {
      Assert.assertTrue(o.getVoidReason().equals("test void reason"));
    }
  }
  @Test
  @Verifies(value = "should delete encounter correctly", method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldDeleteEncounter() throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 3, 5000, date); // adding an un-matched, voided Obs
    for (Obs o : e.getAllObs(true)) {
      o.setVoided(true);
      o.setVoidedBy(Context.getUserService().getUser(1));
      o.setVoidReason("blah");
      o.setDateVoided(new Date());
    }

    // and adding a voided drug order
    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setVoided(true);
    dor.setVoidedBy(Context.getUserService().getUser(1));
    dor.setVoidReason("blah");
    dor.setDateVoided(new Date());
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

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

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // encounter had no non-voided objects, should be voided
    Assert.assertTrue(e.isVoided());
  }
  @Test
  public void getBedsForWard_gets_all_bed_layouts_for_ward() {
    LocationService locationService = Context.getLocationService();

    Location ward = locationService.getLocationByUuid("19e023e8-20ee-4237-ade6-9e68f897b7a9");
    AdmissionLocation admissionLocation = bedManagementService.getLayoutForWard(ward);

    assertEquals(6, admissionLocation.getBedLayouts().size());
    assertEquals(
        "Physical Location for Orthopaedic ward",
        admissionLocation.getBedLayouts().get(0).getLocation());
  }
  /**
   * @verifies return cashpoints that start with the specified name
   * @see ICashPointService#getCashPointsByLocationAndName(org.openmrs.Location, String, boolean)
   */
  @Test
  public void getCashPointsByLocationAndName_shouldReturnCashpointsThatStartWithTheSpecifiedName()
      throws Exception {
    List<CashPoint> results =
        service.getCashPointsByLocationAndName(
            Context.getLocationService().getLocation(0), "Test 1", false);
    Assert.assertNotNull(results);
    Assert.assertEquals(1, results.size());
    Assert.assertEquals(0, (int) Iterators.get(results.iterator(), 0).getId());

    CashPoint cashPoint = service.getById(0);
    assertEntity(cashPoint, results.get(0));

    List<CashPoint> results1 =
        service.getCashPointsByLocationAndName(
            Context.getLocationService().getLocation(2), "Test", false);
    Assert.assertNotNull(results1);
    Assert.assertEquals(2, results1.size());
    Assert.assertEquals(2, (int) Iterators.get(results1.iterator(), 0).getId());
    Assert.assertEquals(6, (int) Iterators.get(results1.iterator(), 1).getId());
  }
  /**
   * @verifies return all cashpoints for the specified location
   * @see ICashPointService#getCashPointsByLocation(org.openmrs.Location, boolean)
   */
  @Test
  public void getCashPointsByLocation_shouldReturnAllCashpointsForTheSpecifiedLocation()
      throws Exception {
    List<CashPoint> cashPoint =
        service.getCashPointsByLocation(Context.getLocationService().getLocation(0), false);
    Assert.assertNotNull(cashPoint);
    Assert.assertEquals(3, cashPoint.size());

    Assert.assertEquals(0, (int) Iterators.get(cashPoint.iterator(), 0).getId());
    Assert.assertEquals(4, (int) Iterators.get(cashPoint.iterator(), 1).getId());
    Assert.assertEquals(5, (int) Iterators.get(cashPoint.iterator(), 2).getId());
  }
Exemplo n.º 17
0
  /**
   * Adds a new encounter with the given observations and orders.
   *
   * @param observations a list of observations
   * @param orderUuids a list of order UUIDs
   * @param patient the patient for whom to add the encounter
   * @param encounterTime the time of the encounter
   * @param changeMessage a message to be recorded with the observation
   * @param encounterTypeName the OpenMRS name for the encounter type, configured in OpenMRS
   * @param locationUuid the UUID of the location where the encounter happened
   */
  public static Encounter addEncounter(
      List observations,
      List orderUuids,
      Patient patient,
      Date encounterTime,
      String changeMessage,
      String encounterTypeName,
      String locationUuid) {
    // OpenMRS will reject the encounter if the time is in the past, even if
    // the client's clock is off by only one millisecond; work around this.
    encounterTime = Utils.fixEncounterDateTime(encounterTime);

    EncounterService encounterService = Context.getEncounterService();
    final Location location = Context.getLocationService().getLocationByUuid(locationUuid);
    if (location == null) {
      throw new InvalidObjectDataException("Location not found: " + locationUuid);
    }
    EncounterType encounterType = encounterService.getEncounterType(encounterTypeName);
    if (encounterType == null) {
      throw new InvalidObjectDataException("Encounter type not found: " + encounterTypeName);
    }

    List<Obs> obsList = new ArrayList<>();
    if (observations != null) {
      for (Object observation : observations) {
        obsList.add(jsonObservationToObs(observation, patient, encounterTime, location));
      }
    }

    if (orderUuids != null) {
      for (Object item : orderUuids) {
        obsList.add(orderUuidToObs((String) item, patient, encounterTime, location));
      }
    }

    // Write the encounter and all the observations to the database.
    Encounter encounter = new Encounter();
    encounter.setEncounterDatetime(encounterTime);
    encounter.setPatient(patient);
    encounter.setLocation(location);
    encounter.setEncounterType(encounterType);
    encounter = encounterService.saveEncounter(encounter);

    ObsService obsService = Context.getObsService();
    for (Obs obs : obsList) {
      if (obs != null) {
        encounter.addObs(obs);
        obsService.saveObs(obs, changeMessage);
      }
    }
    return encounter;
  }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldHandleDrugOrderAndObsCorrectly()
      throws Exception {
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));
    Encounter e = new Encounter();
    e.setPatient(Context.getPatientService().getPatient(2));
    Date date = Context.getDateFormat().parse("01/02/2003");
    e.setDateCreated(new Date());
    e.setEncounterDatetime(date);
    e.setLocation(Context.getLocationService().getLocation(2));
    e.setProvider(Context.getPersonService().getPerson(502));
    TestUtil.addObs(e, 3, 5000, date); // adding an un-matched Obs

    DrugOrder dor = new DrugOrder();
    dor.setVoided(false);
    dor.setConcept(Context.getConceptService().getConcept(792));
    dor.setCreator(Context.getUserService().getUser(1));
    dor.setDateCreated(new Date());
    dor.setDiscontinued(false);
    dor.setDrug(Context.getConceptService().getDrug(2));
    dor.setOrderType(Context.getOrderService().getOrderType(1));
    dor.setPatient(Context.getPatientService().getPatient(2));
    dor.setStartDate(new Date());
    e.addOrder(dor);

    Context.getEncounterService().saveEncounter(e);

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

    HtmlFormEntryUtil.voidEncounterByHtmlFormSchema(e, htmlform, null);

    // order was matched, obs was not, so order should be voided, obs not, encounter not.
    Assert.assertTrue(!e.isVoided());
    for (Order o : e.getOrders()) {
      Assert.assertTrue(o.isVoided());
    }
    for (Obs o : e.getObs()) {
      Assert.assertTrue(!o.isVoided());
    }
  }
Exemplo n.º 19
0
 /** Gets a Location entity by its exact name. */
 public static Location getLocationByName(String locationName, Location parent) {
   LocationService locationService = Context.getLocationService();
   Location location = locationService.getLocation(locationName);
   if (location == null) {
     location = new Location();
     location.setName(locationName);
     location.setDescription(locationName);
     if (parent != null) {
       location.setParentLocation(parent);
     }
     locationService.saveLocation(location);
   }
   return location;
 }
  @Test
  public void shouldReturnBedAssignmentDetailsByPatient() {
    PatientService patientService = Context.getPatientService();
    Patient patient = patientService.getPatient(3);

    LocationService locationService = Context.getLocationService();
    Location ward = locationService.getLocation(123452);
    String bedNumFromDataSetup = "307-a";

    BedDetails bedDetails = bedManagementService.getBedAssignmentDetailsByPatient(patient);
    assertEquals(ward.getId(), bedDetails.getPhysicalLocation().getId());
    assertEquals(bedIdFromDataSetup, bedDetails.getBedId());
    assertEquals(bedNumFromDataSetup, bedDetails.getBedNumber());
  }
Exemplo n.º 21
0
  /**
   * * Get the location by: 1)an integer id like 5090 or 2) uuid like
   * "a3e12268-74bf-11df-9768-17cfc9833272" or 3) location name like "Boston"
   *
   * @param Id
   * @return the location if exist, else null
   * @should find a location by its locationId
   * @should find a location by name
   * @should find a location by its uuid
   * @should return null otherwise
   */
  public static Location getLocation(String id) {
    Location location = null;

    if (id != null) {

      try { // handle integer: id
        int locationId = Integer.parseInt(id);
        location = Context.getLocationService().getLocation(locationId);
        return location;
      } catch (Exception ex) {
        // do nothing
      }

      // handle uuid id: "a3e1302b-74bf-11df-9768-17cfc9833272" if id matches a uuid pattern
      if (Pattern.compile("\\w+-\\w+-\\w+-\\w+-\\w+").matcher(id).matches()) {
        location = Context.getLocationService().getLocationByUuid(id);
        return location;
      } else {
        // if it's neither a uuid or id, try location name
        location = Context.getLocationService().getLocation(id);
      }
    }
    return location;
  }
  /** @see EmrVisitAssignmentHandler#checkLocations(org.openmrs.Visit, org.openmrs.Encounter) */
  @Test
  public void checkLocations() {
    Patient patient = TestUtils.getPatient(7);
    Form moh257 = MetadataUtils.getForm(HivMetadata._Form.MOH_257_VISIT_SUMMARY);
    VisitType outpatient = MetadataUtils.getVisitType(CommonMetadata._VisitType.OUTPATIENT);

    // Save regular visit on Jan 1st at no specific location
    Visit visit0 = TestUtils.saveVisit(patient, outpatient, TestUtils.date(2012, 1, 1), null);

    // Save regular visit on Jan 1st at location #2
    Visit visit1 = TestUtils.saveVisit(patient, outpatient, TestUtils.date(2012, 1, 1), null);
    visit1.setLocation(Context.getLocationService().getLocation(1));

    // Save regular visit on Jan 1st at location #2
    Visit visit2 = TestUtils.saveVisit(patient, outpatient, TestUtils.date(2012, 1, 1), null);
    visit2.setLocation(Context.getLocationService().getLocation(2));

    // Save MOH257 for that day (will default to location #1)
    Encounter encounter = TestUtils.saveEncounter(patient, moh257, TestUtils.date(2012, 1, 1));

    Assert.assertThat(EmrVisitAssignmentHandler.checkLocations(visit0, encounter), is(true));
    Assert.assertThat(EmrVisitAssignmentHandler.checkLocations(visit1, encounter), is(true));
    Assert.assertThat(EmrVisitAssignmentHandler.checkLocations(visit2, encounter), is(false));
  }
  @Override
  public CashPoint createEntity(boolean valid) {
    CashPoint cashPoint = new CashPoint();

    if (valid) {
      cashPoint.setName("Test Cash Point");
    }

    cashPoint.setDescription("Test description");
    cashPoint.setLocation(Context.getLocationService().getLocation(1));
    cashPoint.setCreator(Context.getAuthenticatedUser());
    cashPoint.setDateCreated(new Date());

    return cashPoint;
  }
  private void setupMappings() {
    MetadataSource metadataSource = new MetadataSource();
    metadataSource.setName("source");
    metadataSource.setDateCreated(new Date());
    metadataSource.setRetired(false);
    metadataSource.setId(1);
    metadataSource =
        Context.getService(MetadataMappingService.class).saveMetadataSource(metadataSource);

    MetadataTermMapping metadataTermMapping1 =
        new MetadataTermMapping(
            metadataSource, "DataClerk", Context.getUserService().getRole("Data Clerk"));
    metadataTermMapping1.setName("mapping1");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping1);

    MetadataTermMapping metadataTermMapping2 =
        new MetadataTermMapping(
            metadataSource, "ROLE", Context.getUserService().getRole("Provider"));
    metadataTermMapping2.setName("mapping2");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping2);

    MetadataTermMapping metadataTermMapping3 =
        new MetadataTermMapping(
            metadataSource,
            "Location",
            Context.getLocationService().getLocationByUuid("9356400c-a5a2-4532-8f2b-2361b3446eb8"));
    metadataTermMapping3.setName("mapping3");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping3);

    MetadataTermMapping metadataTermMapping4 =
        new MetadataTermMapping(
            metadataSource,
            "MDR-TB PROGRAM",
            Context.getProgramWorkflowService().getProgramByName("MDR-TB PROGRAM"));
    metadataTermMapping4.setName("mapping4");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping4);

    MetadataTermMapping metadataTermMapping5 =
        new MetadataTermMapping(
            metadataSource, "1", Context.getPatientService().getPatientIdentifierType(1));
    metadataTermMapping5.setName("mapping5");
    Context.getService(MetadataMappingService.class).saveMetadataTermMapping(metadataTermMapping5);

    Context.flushSession();
  }
  /**
   * This is called prior to displaying a form for the first time. It tells Spring the form/command
   * object to load into the request
   *
   * @see
   *     org.springframework.web.servlet.mvc.AbstractFormController#formBackingObject(javax.servlet.http.HttpServletRequest)
   * @should return valid location given valid locationId
   */
  protected Object formBackingObject(HttpServletRequest request) throws ServletException {

    Location location = null;

    if (Context.isAuthenticated()) {
      LocationService ls = Context.getLocationService();
      String locationId = request.getParameter("locationId");
      if (locationId != null) {
        location = ls.getLocation(Integer.valueOf(locationId));
      }
    }

    if (location == null) {
      location = new Location();
    }

    return location;
  }
  /**
   * @verifies not return retired cashpoints unless specified
   * @see ICashPointService#getCashPointsByLocationAndName(org.openmrs.Location, String, boolean)
   */
  @Test
  public void getCashPointsByLocationAndName_shouldNotReturnRetiredCashpointsUnlessSpecified()
      throws Exception {
    CashPoint cashPoint = service.getById(0);
    cashPoint.setRetired(true);
    cashPoint.setRetireReason("reason");
    service.save(cashPoint);
    Location location = Context.getLocationService().getLocation(0);

    Context.flushSession();

    List<CashPoint> results = service.getCashPointsByLocationAndName(location, "Test", false);
    Assert.assertNotNull(results);
    Assert.assertEquals(2, results.size());
    Assert.assertEquals(4, (int) Iterators.get(results.iterator(), 0).getId());
    Assert.assertEquals(5, (int) Iterators.get(results.iterator(), 1).getId());

    List<CashPoint> results1 = service.getCashPointsByLocationAndName(location, "Test", true);
    Assert.assertNotNull(results1);
    Assert.assertEquals(3, results1.size());
    Assert.assertEquals(0, (int) Iterators.get(results1.iterator(), 0).getId());
  }
  /**
   * Searches for locations by name of MFL code
   *
   * @param term the search term
   * @return the list of locations as simple objects
   */
  public List<SimpleObject> locations(
      @RequestParam("term") String term, UiUtils ui, @SpringBean KenyaEmrUiUtils kenyaUi) {
    LocationService svc = Context.getLocationService();
    LocationAttributeType mflCodeAttrType =
        Metadata.getLocationAttributeType(Metadata.MASTER_FACILITY_CODE_LOCATION_ATTRIBUTE_TYPE);

    // Results will be sorted by name
    Set<Location> results =
        new TreeSet<Location>(
            new Comparator<Location>() {
              @Override
              public int compare(Location location1, Location location2) {
                return location1.getName().compareTo(location2.getName());
              }
            });

    // If term looks like an MFL code, add location with that code
    if (StringUtils.isNumeric(term) && term.length() >= 5) {
      Location locationByMflCode =
          Context.getService(KenyaEmrService.class).getLocationByMflCode(term);
      if (locationByMflCode != null) {
        results.add(locationByMflCode);
      }
    }

    // Add first 20 results of search by name
    if (StringUtils.isNotBlank(term)) {
      results.addAll(svc.getLocations(term, true, 0, 20));
    }

    // Convert to simple objects
    List<SimpleObject> ret = new ArrayList<SimpleObject>();
    for (Location l : results) {
      ret.add(kenyaUi.simpleLocation(l, mflCodeAttrType, ui));
    }
    return ret;
  }
  /** Edit a new or existing AutoGeneration Option */
  @RequestMapping("/module/idgen/editAutoGenerationOption")
  public void editAutoGenerationOption(
      ModelMap model,
      HttpServletRequest request,
      @RequestParam(required = false, value = "autoGenerationOption")
          AutoGenerationOption option, // expects to get either an option or an identifier type
      @RequestParam(required = false, value = "identifierType") PatientIdentifierType type) {

    if (Context.isAuthenticated()) {
      Thread.currentThread().setContextClassLoader(OpenmrsClassLoader.getInstance());

      IdentifierSourceService iss = Context.getService(IdentifierSourceService.class);
      LocationService locationService = Context.getLocationService();

      if (option == null) {
        option = new AutoGenerationOption(type);
      }

      model.addAttribute("option", option);
      model.addAttribute(
          "availableSources", iss.getIdentifierSourcesByType(true).get(option.getIdentifierType()));
      model.addAttribute("availableLocations", locationService.getAllLocations());
    }
  }
  @Test
  @Verifies(
      value = "should create cloned form without locations, providers, and patient identifiers",
      method = "createCloneForExport(HtmlForm)")
  public void createCloneForExport_shouldCreateCloneButSkipLocationsAndProviders()
      throws Exception {

    // include this set so that we get the mapping concept
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_HTML_FORM_ENTRY_TEST_DATASET));

    HtmlForm form = new HtmlForm();
    form.setXmlData(
        new TestUtil().loadXmlFromFile(XML_DATASET_PATH + "metadataSharingTestForm.xml"));

    HtmlFormExporter exporter = new HtmlFormExporter(form);
    HtmlForm formClone = exporter.export(false, false, false, false);

    Collection<OpenmrsObject> dependencies = formClone.getDependencies();

    // make sure the provider has NOT been added to the list of dependencies
    Assert.assertFalse(
        dependencies.contains(
            Context.getPersonService().getPersonByUuid("c04ee3c8-b68f-43cc-bff3-5a831ee7225f")));

    // make sure the locations have NOT been added to the dependencies
    Assert.assertFalse(
        dependencies.contains(
            Context.getLocationService()
                .getLocationByUuid("dc5c1fcc-0459-4201-bf70-0b90535ba362")));
    Assert.assertFalse(
        dependencies.contains(
            Context.getLocationService()
                .getLocationByUuid("9356400c-a5a2-4532-8f2b-2361b3446eb8")));

    // make sure the patient identifier types have NOT been added to the list of dependencies
    Assert.assertFalse(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("1a339fe9-38bc-4ab3-b180-320988c0b968")));
    Assert.assertFalse(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("2f470aa8-1d73-43b7-81b5-01f0c0dfa53c")));

    // make sure the roles have NOT been added to the list of dependencies
    Assert.assertFalse(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("92b70b00-58b1-11e0-80e3-0800200c9a66")));
    Assert.assertFalse(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("a238c500-58b1-11e0-80e3-0800200c9a66")));

    /* We have changed the default so that you cannot exclude mapped concepts or drugs referenced by name */
    // Assert.assertFalse(dependencies.contains(Context.getConceptService().getConceptByUuid(
    // "44d3611a-6699-4d52-823f-b4b788bac3e3")));
    // make sure the drug referenced by name has NOT been added to the dependencies
    // Assert.assertFalse(dependencies.contains(Context.getConceptService().getDrugByUuid(
    // "05ec820a-d297-44e3-be6e-698531d9dd3f")));

  }
  @Test
  public void shouldRespectClassesNotToExportGlobalProperty() throws Exception {

    // include this set so that we get the mapping concept
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_HTML_FORM_ENTRY_TEST_DATASET));
    Context.getAdministrationService()
        .saveGlobalProperty(
            new GlobalProperty(
                HtmlFormEntryConstants.GP_CLASSES_NOT_TO_EXPORT_WITH_MDS, "org.openmrs.Program"));

    HtmlForm form = new HtmlForm();
    form.setXmlData(
        new TestUtil().loadXmlFromFile(XML_DATASET_PATH + "metadataSharingTestForm.xml"));

    HtmlFormExporter exporter = new HtmlFormExporter(form);
    HtmlForm formClone = exporter.export(true, true, true, true);

    Collection<OpenmrsObject> dependencies = formClone.getDependencies();

    // make sure all the appropriate concepts have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc1")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc4")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc5")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc6")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-03aa-102d-b0e3-001ec94a0cc3")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("aa52296060-03-102d-b0e3-001ec94a0cc1")));
    // this is the mapped concept XYZ:HT found in HtmlFormEntryTest-data
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("44d3611a-6699-4d52-823f-b4b788bac3e3")));

    // drug discontinue reason, corresponds to concept 555 in regressionTest-data
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getConceptByUuid("32296060-0370-102d-b0e3-123456789011")));

    // make sure the programs have NOT been added to the dependencies
    Assert.assertFalse(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getProgramByUuid("da4a0391-ba62-4fad-ad66-1e3722d16380")));
    Assert.assertFalse(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getProgramByUuid("71779c39-d289-4dfe-91b5-e7cfaa27c78b")));

    // make sure the program workflows have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getWorkflowByUuid("72a90efc-5140-11e1-a3e3-00248140a5eb")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getWorkflowByUuid("7c3e071a-53a7-11e1-8cb6-00248140a5eb")));

    // make sure the program workflow states have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("92584cdc-6a20-4c84-a659-e035e45d36b0")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("e938129e-248a-482a-acea-f85127251472")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("860b3a13-d4b1-4f0a-b526-278652fa1809")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("8ef66ca8-5140-11e1-a3e3-00248140a5eb")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getProgramWorkflowService()
                .getStateByUuid("67337cdc-53ad-11e1-8cb6-00248140a5eb")));

    // make sure the drugs have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("3cfcf118-931c-46f7-8ff6-7b876f0d4202")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("05ec820a-d297-44e3-be6e-698531d9dd3f")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getConceptService().getDrugByUuid("7e2323fa-0fa0-461f-9b59-6765997d849e")));

    // make sure the locations have been added to the dependencies
    Assert.assertTrue(
        dependencies.contains(Context.getLocationService().getLocation("Never Never Land")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getLocationService()
                .getLocationByUuid("9356400c-a5a2-4532-8f2b-2361b3446eb8")));
    Assert.assertTrue(dependencies.contains(Context.getLocationService().getLocation(1)));

    // make sure the provider has been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getPersonService().getPersonByUuid("c04ee3c8-b68f-43cc-bff3-5a831ee7225f")));

    // make sure the patient identifier types have been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("1a339fe9-38bc-4ab3-b180-320988c0b968")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getPatientService()
                .getPatientIdentifierTypeByUuid("2f470aa8-1d73-43b7-81b5-01f0c0dfa53c")));

    // make sure the roles have been added to the list of dependencies
    Assert.assertTrue(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("92b70b00-58b1-11e0-80e3-0800200c9a66")));
    Assert.assertTrue(
        dependencies.contains(
            Context.getUserService().getRoleByUuid("a238c500-58b1-11e0-80e3-0800200c9a66")));
  }