/** @see {@link OrderValidator#validate(Object,Errors)} */
  @Test
  @Verifies(
      value = "should pass validation if field lengths are correct",
      method = "validate(Object,Errors)")
  public void validate_shouldPassValidationIfFieldLengthsAreCorrect() throws Exception {
    Order order = new Order();
    Encounter encounter = new Encounter();
    order.setConcept(Context.getConceptService().getConcept(88));
    order.setOrderer(Context.getProviderService().getProvider(1));
    Patient patient = Context.getPatientService().getPatient(2);
    encounter.setPatient(patient);
    order.setPatient(patient);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1);
    order.setDateActivated(cal.getTime());
    order.setAutoExpireDate(new Date());
    order.setCareSetting(new CareSetting());
    order.setEncounter(encounter);
    order.setUrgency(Order.Urgency.ROUTINE);
    order.setAction(Order.Action.NEW);

    order.setOrderReasonNonCoded("orderReasonNonCoded");
    order.setAccessionNumber("accessionNumber");
    order.setCommentToFulfiller("commentToFulfiller");
    order.setVoidReason("voidReason");

    Errors errors = new BindException(order, "order");
    new OrderValidator().validate(order, errors);

    Assert.assertFalse(errors.hasErrors());
  }
  /**
   * Processes requests to retire concept reference terms
   *
   * @param request the {@link WebRequest} object
   * @param conceptReferenceTermModel the concept reference term model for the term to retire
   * @param retireReason the reason why the concept reference term is being retired
   * @return the url to redirect to
   */
  @RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/retireConceptReferenceTerm")
  public String retireConceptReferenceTerm(
      WebRequest request,
      @ModelAttribute(value = "conceptReferenceTermModel")
          ConceptReferenceTermModel conceptReferenceTermModel,
      @RequestParam(required = false, value = "retireReason") String retireReason) {

    if (!StringUtils.hasText(retireReason)) {
      retireReason = Context.getMessageSourceService().getMessage("general.default.retireReason");
    }

    try {
      ConceptReferenceTerm conceptReferenceTerm =
          conceptReferenceTermModel.getConceptReferenceTerm();
      Context.getConceptService().retireConceptReferenceTerm(conceptReferenceTerm, retireReason);
      if (log.isDebugEnabled()) {
        log.debug("Retired concept reference term with id: " + conceptReferenceTerm.getId());
      }
      request.setAttribute(
          WebConstants.OPENMRS_MSG_ATTR,
          Context.getMessageSourceService().getMessage("ConceptReferenceTerm.retired"),
          WebRequest.SCOPE_SESSION);

      return "redirect:" + FIND_CONCEPT_REFERENCE_TERM_URL;
    } catch (APIException e) {
      log.error("Error occurred while retiring concept reference term", e);
      request.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR,
          Context.getMessageSourceService().getMessage("ConceptReferenceTerm.retire.error"),
          WebRequest.SCOPE_SESSION);
    }

    // an error occurred
    return CONCEPT_REFERENCE_TERM_FORM;
  }
  /**
   * Processes requests to purge a concept reference term
   *
   * @param request the {@link WebRequest} object
   * @param conceptReferenceTermModel
   * @return the url to forward to
   */
  @RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/purgeConceptReferenceTerm")
  public String purgeTerm(
      WebRequest request,
      @ModelAttribute(value = "conceptReferenceTermModel")
          ConceptReferenceTermModel conceptReferenceTermModel) {
    Integer id = conceptReferenceTermModel.getConceptReferenceTerm().getId();
    try {
      Context.getConceptService()
          .purgeConceptReferenceTerm(conceptReferenceTermModel.getConceptReferenceTerm());
      if (log.isDebugEnabled()) {
        log.debug("Purged concept reference term with id: " + id);
      }
      request.setAttribute(
          WebConstants.OPENMRS_MSG_ATTR,
          Context.getMessageSourceService().getMessage("ConceptReferenceTerm.purged"),
          WebRequest.SCOPE_SESSION);
      return "redirect:" + FIND_CONCEPT_REFERENCE_TERM_URL;
    } catch (APIException e) {
      log.warn("Error occurred while attempting to purge concept reference term", e);
      request.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR,
          Context.getMessageSourceService().getMessage("ConceptReferenceTerm.purge.error"),
          WebRequest.SCOPE_SESSION);
    }

    // send the user back to form
    return "redirect:" + CONCEPT_REFERENCE_TERM_FORM_URL + ".form?conceptReferenceTermId=" + id;
  }
  /**
   * gets patients pediatrics who have adult who stage
   *
   * @param session
   * @return patientsPediatricsWhoHaveAdultWhoStage
   */
  public List<Patient> getPatientsPediatricsWhoHaveAdultWhoStage() {
    List<Patient> patientsInHIVProgram = new ArrayList<Patient>();
    List<Patient> patientsPediatricsInHIVProgram = new ArrayList<Patient>();

    List<Patient> patientsPediatricsWhoHaveAdultWhoStage = new ArrayList<Patient>();
    List<Patient> patientsWhoHaveAdultWhoStage = new ArrayList<Patient>();
    //		List<Person> persons = new ArrayList<Person>();
    //		List<Obs> observers = new ArrayList<Obs>();
    ProgramWorkflowService programService = Context.getProgramWorkflowService();
    Program program = programService.getProgram(2);

    patientsInHIVProgram = getPatientsCurrentlyInHIVProgram(program);

    for (Patient patient : patientsInHIVProgram) {
      if (patient.getAge() < 15) {
        patientsPediatricsInHIVProgram.add(patient);
      }
    }
    DataQualityService dqs = ((DataQualityService) Context.getService(DataQualityService.class));
    List<Integer> patientIds = dqs.getPatientsWhoHaveAdultWhoStage();
    for (Integer patientId : patientIds) {
      patientsWhoHaveAdultWhoStage.add(getPatientById(patientId));
    }

    for (Patient patient : patientsWhoHaveAdultWhoStage) {
      if (patientsPediatricsInHIVProgram.contains(patient)) {
        patientsPediatricsWhoHaveAdultWhoStage.add(patient);
      }
    }

    return patientsPediatricsWhoHaveAdultWhoStage;
  }
  /** @see org.openmrs.module.web.extension.AdministrationSectionExt#getLinks() */
  @Override
  public Map<String, String> getLinks() {
    Map<String, String> map = new LinkedHashMap<String, String>();

    if (Context.hasPrivilege(ReportingConstants.PRIV_RUN_REPORTS)) {
      map.put("module/amrsreports/mohRender.form", "Run AMRS Reports");
    }

    if (Context.hasPrivilege(ReportingConstants.PRIV_VIEW_REPORTS)) {
      map.put("module/amrsreports/mohHistory.form", "View AMRS Reports");
    }

    if (Context.hasPrivilege(PrivilegeConstants.VIEW_LOCATIONS)) {
      map.put("module/amrsreports/facility.list", "View MOH Facilities");
    }

    if (Context.hasPrivilege(ReportingConstants.PRIV_RUN_REPORTS)) {
      map.put("/module/amrsreports/cohortCounts.list", "View Cohort Counts");
    }

    if (Context.hasPrivilege(ReportingConstants.PRIV_RUN_REPORTS)) {
      map.put("module/amrsreports/locationPrivileges.form", "Location Privileges");
    }

    map.put("module/amrsreports/settings.form", "Settings");

    return map;
  }
  /**
   * Processes requests to retire a concept map type
   *
   * @param request the {@link WebRequest} object
   * @param conceptMapType the concept map type object to retire
   * @param retireReason the reason why the concept map type is getting retired
   * @return the url to redirect to
   */
  @RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/retireConceptMapType")
  public String retireConceptMapType(
      WebRequest request,
      @ModelAttribute(value = "conceptMapType") ConceptMapType conceptMapType,
      @RequestParam(required = false, value = "retireReason") String retireReason) {

    if (!StringUtils.hasText(retireReason)) {
      retireReason = Context.getMessageSourceService().getMessage("general.default.retireReason");
    }

    try {
      Context.getConceptService().retireConceptMapType(conceptMapType, retireReason);
      if (log.isDebugEnabled()) {
        log.debug("Retired concept map type with id: " + conceptMapType.getId());
      }
      request.setAttribute(
          WebConstants.OPENMRS_MSG_ATTR,
          Context.getMessageSourceService().getMessage("ConceptMapType.retired"),
          WebRequest.SCOPE_SESSION);

      return "redirect:" + CONCEPT_MAP_TYPE_LIST_URL + ".list";
    } catch (APIException e) {
      log.error("Error occurred while attempting to retire concept map type", e);
      request.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR,
          Context.getMessageSourceService().getMessage("ConceptMapType.retire.error"),
          WebRequest.SCOPE_SESSION);
    }

    // an error occurred
    return CONCEPT_MAP_TYPE_FORM;
  }
  /**
   * @see RegimenManager#findDefinitions(String, org.openmrs.module.kenyaemr.regimen.RegimenOrder,
   *     boolean)
   */
  @Test
  public void findDefinitions_shouldFindDefinitionsForRegimen() {
    // Create regimen that matches the regimen2 definition exactly
    DrugOrder lamivudine = new DrugOrder();
    lamivudine.setConcept(Context.getConceptService().getConcept(78643));
    lamivudine.setDose(150d);
    lamivudine.setUnits("mg");
    lamivudine.setFrequency("BD");
    DrugOrder stavudine = new DrugOrder();
    stavudine.setConcept(Context.getConceptService().getConcept(84309));
    stavudine.setDose(30d);
    stavudine.setUnits("mg");
    stavudine.setFrequency("OD");
    RegimenOrder regimen =
        new RegimenOrder(new HashSet<DrugOrder>(Arrays.asList(lamivudine, stavudine)));

    // Test exact match
    List<RegimenDefinition> defsExact = regimenManager.findDefinitions("category1", regimen, true);
    Assert.assertEquals(1, defsExact.size());
    Assert.assertEquals("regimen2", defsExact.get(0).getName());

    // Test non-exact match
    List<RegimenDefinition> defsNonExact =
        regimenManager.findDefinitions("category1", regimen, false);
    Assert.assertEquals(2, defsNonExact.size());
    Assert.assertEquals("regimen2", defsNonExact.get(0).getName());
    Assert.assertEquals("regimen3", defsNonExact.get(1).getName());
  }
  public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ModelMap model = new ModelMap();
    // Integer patientId = (Integer) request.getAttribute("patientId");
    String patientIdStr = (String) request.getParameter("patientId");
    Integer patientId = Integer.valueOf(patientIdStr);
    Patient p = Context.getPatientService().getPatient(patientId);
    System.out.println(
        "PatientNotesPortletController handleRequest **************************\n"
            + "Patient id: "
            + patientIdStr);
    model.put("patient", p);
    List<Note> nots = Context.getService(NoteService.class).getNotesByPatient(p);
    ArrayList<Note> notes = new ArrayList<Note>();
    if (nots.size() > 4) {
      for (int i = 0; i < 4; i++) {
        notes.add(nots.get(i));
      }
    } else {
      notes.addAll(nots);
    }
    model.put("notes", notes);

    String filepath;
    // Put any files for reading in the following directory - unix/windows
    if (OpenmrsConstants.UNIX_BASED_OPERATING_SYSTEM) {
      filepath = System.getProperty("user.home") + File.separator + ".OpenMRS";
    } else {
      filepath =
          System.getProperty("user.home")
              + File.separator
              + "Application Data"
              + File.separator
              + "OpenMRS";
    }

    filepath = filepath + File.separator;
    File folder = new File(filepath);

    if (!folder.exists()) {
      model.put("prop", "NO SUCH FILE");
      return new ModelAndView("/module/basicmodule/portlets/patientNotes", model);
    }
    BufferedReader r;
    try {
      String line = "";
      r = new BufferedReader(new FileReader(filepath + "openmrs-runtime.properties.txtt"));
      for (int i = 0; i < 3; i++) {
        line += r.readLine() + "<br>";
      }
      System.out.println(
          "Property file: " + filepath + "openmrs-runtime.properties.txtt" + "   Line: " + line);
      model.put("prop", line);
      r.close();
    } catch (Exception ex) {
      Logger.getLogger(PatientNotesController.class.getName()).log(Level.SEVERE, null, ex);
    }

    return new ModelAndView("/module/basicmodule/portlets/patientNotes", model);
  }
  /**
   * @see LabCatalogService#getLabTestPanels(String,Boolean,Integer,Integer)
   * @verifies return LabTestPanel by String nameFragment, Boolean includeVoided, Integer start,
   *     Integer length
   */
  @Test
  public void
      getLabTestPanels_shouldReturnLabTestPanelByStringNameFragmentBooleanIncludeVoidedIntegerStartIntegerLength()
          throws Exception {
    List<LabTestPanel> list;

    // verify default case works like getAllLabTestPanels()
    list = Context.getService(LabCatalogService.class).getLabTestPanels("", Boolean.FALSE, 0, 4);
    Assert.assertNotNull("getAllLabTestPanels should not return null", list);
    Assert.assertEquals("getAllLabTestPanels should return the right objects", 4, list.size());

    // verify get by nameFragment
    list =
        Context.getService(LabCatalogService.class)
            .getLabTestPanels("Hematology Panel", Boolean.FALSE, 0, 4);
    Assert.assertNotNull("getLabTestPanels should not return null", list);
    Assert.assertEquals(
        "getLabTestPanels should return the right object when using name fragment",
        "05de81e6-46d9-11e1-99f4-0024e8c61285",
        list.get(0).getUuid());

    // verify start and length restrictions
    list = Context.getService(LabCatalogService.class).getLabTestPanels("", Boolean.FALSE, 1, 2);
    Assert.assertNotNull("getLabTestPanels should not return null", list);
    Assert.assertEquals(
        "getLabTestPanels should return the right amount of objects", 2, list.size());
    Assert.assertEquals(
        "getLabTestPanels should return the right object",
        "05dec1ac-46d9-11e1-99f4-0024e8c61285",
        list.get(0).getUuid());
    Assert.assertEquals(
        "getLabTestPanels should return the right object",
        "05df00e1-46d9-11e1-99f4-0024e8c61285",
        list.get(1).getUuid());
  }
Example #10
0
  /**
   * Gets a concept by an identifier (mapping or UUID)
   *
   * @param identifier the identifier
   * @return the concept
   * @throws org.openmrs.module.metadatadeploy.MissingMetadataException if the concept could not be
   *     found
   */
  public static Concept getConcept(String identifier) {
    Concept concept;

    if (identifier.contains(":")) {
      String[] tokens = identifier.split(":");
      concept = Context.getConceptService().getConceptByMapping(tokens[1].trim(), tokens[0].trim());
    } else {
      // Assume it's a UUID
      concept = Context.getConceptService().getConceptByUuid(identifier);
    }

    if (concept == null) {
      throw new MissingMetadataException(Concept.class, identifier);
    }

    // getConcept doesn't always return ConceptNumeric for numeric concepts
    if (concept.getDatatype().isNumeric() && !(concept instanceof ConceptNumeric)) {
      concept = Context.getConceptService().getConceptNumeric(concept.getId());

      if (concept == null) {
        throw new MissingMetadataException(ConceptNumeric.class, identifier);
      }
    }

    return concept;
  }
  private List<String> getRefTermAncestors(
      UiSessionContext context, String id, Locale locale, ConceptSource conceptSource)
      throws Exception {

    ConceptService conceptService = (ConceptService) Context.getService(ConceptService.class);

    ConceptManagementAppsService conceptManagementAppsService =
        (ConceptManagementAppsService) Context.getService(ConceptManagementAppsService.class);

    // there are no mappings so we need to send it through blank and let the user know
    if (StringUtils.isEmpty(id) || StringUtils.isBlank(id) || id.contains("empty")) {

      id = "0";
      Set<ConceptReferenceTerm> parentTerms = new HashSet<ConceptReferenceTerm>();
      Set<ConceptReferenceTerm> childTerms = new HashSet<ConceptReferenceTerm>();
      return formatByRefTermForUIWithGson(conceptService, id, childTerms, parentTerms, locale);
    }

    Set<ConceptReferenceTerm> parentTerms =
        conceptManagementAppsService.getRefTermParentReferenceTerms(
            conceptService.getConceptReferenceTerm(Integer.parseInt(id)), conceptSource);

    Set<ConceptReferenceTerm> childTerms =
        conceptManagementAppsService.getRefTermChildReferenceTerms(
            conceptService.getConceptReferenceTerm(Integer.parseInt(id)), conceptSource);

    return formatByRefTermForUIWithGson(conceptService, id, childTerms, parentTerms, locale);
  }
  /** @see Moh731CohortLibrary#revisitsArt() */
  @Test
  public void revisitsArt() throws Exception {
    EncounterType hivConsult =
        MetadataUtils.getEncounterType(HivMetadata._EncounterType.HIV_CONSULTATION);
    Concept stavudine = Context.getConceptService().getConcept(84309);

    // Start patient #6 this month and give them a visit in the reporting period + 2 months
    TestUtils.saveDrugOrder(TestUtils.getPatient(6), stavudine, TestUtils.date(2012, 6, 10), null);
    TestUtils.saveEncounter(TestUtils.getPatient(6), hivConsult, TestUtils.date(2012, 6, 20));

    // Start patient #7 in previous month and give them a visit in the reporting period + 2 months
    TestUtils.saveDrugOrder(TestUtils.getPatient(7), stavudine, TestUtils.date(2012, 5, 10), null);
    TestUtils.saveEncounter(TestUtils.getPatient(7), hivConsult, TestUtils.date(2012, 6, 20));

    // Start patient #8 and give them visit outside of reporting period + 2 month window
    TestUtils.saveDrugOrder(TestUtils.getPatient(8), stavudine, TestUtils.date(2012, 1, 10), null);
    TestUtils.saveEncounter(TestUtils.getPatient(8), hivConsult, TestUtils.date(2012, 1, 20));

    CohortDefinition cd = moh731Cohorts.revisitsArt();
    context.addParameterValue("fromDate", PERIOD_START);
    context.addParameterValue("toDate", PERIOD_END);
    EvaluatedCohort evaluated =
        Context.getService(CohortDefinitionService.class).evaluate(cd, context);
    ReportingTestUtils.assertCohortEquals(Arrays.asList(7), evaluated);
  }
  @Test
  public void evaluate_shouldReturnHivPatientsNotScreenedForTb() throws Exception {

    // Get HIV Program and TB screening encounter type
    Program hivProgram = MetadataUtils.getProgram(Metadata.HIV_PROGRAM);
    EncounterType screeningEncType =
        MetadataUtils.getEncounterType(Metadata.TB_SCREENING_ENCOUNTER_TYPE);

    // Enroll patients #6 and #7
    PatientService ps = Context.getPatientService();
    TestUtils.enrollInProgram(ps.getPatient(6), hivProgram, TestUtils.date(2011, 1, 1));
    TestUtils.enrollInProgram(ps.getPatient(7), hivProgram, TestUtils.date(2011, 1, 1));

    // Screen patient #6 for TB a year later
    TestUtils.saveEncounter(ps.getPatient(6), screeningEncType, TestUtils.date(2012, 1, 1));

    Context.flushSession();

    List<Integer> cohort = Arrays.asList(6, 7, 8);
    CalculationResultMap resultMap =
        Context.getService(PatientCalculationService.class)
            .evaluate(cohort, new NeverScreenedForTbCalculation());
    Assert.assertFalse((Boolean) resultMap.get(6).getValue());
    Assert.assertTrue((Boolean) resultMap.get(7).getValue());
    Assert.assertNull(resultMap.get(8)); // not in HIV program
  }
Example #14
0
  /**
   * Gets the default locale specified as a global property.
   *
   * @return default locale object.
   * @since 1.5
   * @should not return null if global property does not exist
   * @should not fail with empty global property value
   * @should not fail with bogus global property value
   * @should return locale object for global property
   * @should not cache locale when session is not open
   */
  public static Locale getDefaultLocale() {
    if (defaultLocaleCache == null) {
      if (Context.isSessionOpen()) {
        try {
          String locale =
              Context.getAdministrationService()
                  .getGlobalProperty(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE);

          if (StringUtils.hasLength(locale)) {
            try {
              defaultLocaleCache = fromSpecification(locale);
            } catch (Exception t) {
              log.warn("Unable to parse default locale global property value: " + locale, t);
            }
          }
        } catch (Exception e) {
          // swallow most of the stack trace for most users
          log.warn("Unable to get locale global property value. " + e.getMessage());
          log.trace("Unable to get locale global property value", e);
        }

        // if we weren't able to load the locale from the global property,
        // use the default one
        if (defaultLocaleCache == null)
          defaultLocaleCache =
              fromSpecification(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE);
      } else {
        // if session is not open, return the default locale without caching
        return fromSpecification(OpenmrsConstants.GLOBAL_PROPERTY_DEFAULT_LOCALE_DEFAULT_VALUE);
      }
    }

    return defaultLocaleCache;
  }
  /** @see org.openmrs.api.EncounterService#purgeEncounter(Encounter, boolean) */
  public void purgeEncounter(Encounter encounter, boolean cascade) 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.purge",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    if (cascade) {
      ObsService obsService = Context.getObsService();
      List<Encounter> justThisEncounter = new ArrayList<Encounter>();
      justThisEncounter.add(encounter);
      List<Obs> observations = new Vector<Obs>();
      observations.addAll(
          obsService.getObservations(
              null, justThisEncounter, null, null, null, null, null, null, null, null, null, true));
      for (Obs o : observations) {
        obsService.purgeObs(o);
      }
      Set<Order> orders = encounter.getOrders();
      for (Order o : orders) {
        Context.getOrderService().purgeOrder(o);
      }
    }
    Context.getEncounterService().purgeEncounter(encounter);
  }
  @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 List<SimpleObject> getPatients(
      @RequestParam(value = "searchValue", required = true) String searchValue,
      @RequestParam(value = "excludePatientsOf", required = false) Person excludePatientsOf,
      @RequestParam(value = "existingRelationshipTypeToExclude", required = false)
          RelationshipType existingRelationshipTypeToExclude,
      @RequestParam(value = "resultFields[]", required = true) String[] resultFields,
      UiUtils ui)
      throws PersonIsNotProviderException, InvalidRelationshipTypeException {

    if (resultFields == null || resultFields.length == 0) {
      resultFields = new String[] {"personName"};
    }

    // always want to return the id of the result objects
    resultFields = ArrayUtils.add(resultFields, "id");

    // now fetch the results
    List<Patient> patients = Context.getPatientService().getPatients(searchValue);

    // exclude any patients if specified
    if (excludePatientsOf != null && existingRelationshipTypeToExclude != null) {
      List<Patient> patientsToExclude =
          Context.getService(ProviderManagementService.class)
              .getPatientsOfProvider(
                  excludePatientsOf, existingRelationshipTypeToExclude, new Date());
      patients.removeAll(patientsToExclude);
    }

    return SimpleObject.fromCollection(patients, ui, resultFields);
  }
  @Test
  @Verifies(
      value = "should return program enrollment after specified date",
      method = "getClosestFutureProgramEnrollment(Patient,Program,Date)")
  public void shouldReturnPatientProgramWithEnrollmentAfterSpecifiedDate() throws Exception {
    // load this data set so that we get the additional patient program created in this data case
    executeDataSet(
        XML_DATASET_PATH + new TestUtil().getTestDatasetFilename(XML_REGRESSION_TEST_DATASET));

    ProgramWorkflowService pws = Context.getProgramWorkflowService();
    Patient patient = Context.getPatientService().getPatient(2);
    Program program = pws.getProgram(1);

    Calendar cal = Calendar.getInstance();
    cal.set(2001, 6, 31);
    Date date = cal.getTime();

    PatientProgram pp = HtmlFormEntryUtil.getClosestFutureProgramEnrollment(patient, program, date);
    Assert.assertEquals("32296060-03aa-102d-b0e3-001ec94a0cc5", pp.getUuid());

    // now, if we roll the date back a year earlier, it should get the earlier of the two programs
    // for this patient
    cal.set(2000, 6, 31);
    date = cal.getTime();

    pp = HtmlFormEntryUtil.getClosestFutureProgramEnrollment(patient, program, date);
    Assert.assertEquals("32596060-03aa-102d-b0e3-001ec94a0cc5", pp.getUuid());
  }
  /**
   * Processes requests to unretire a concept map type
   *
   * @param request the {@link WebRequest} object
   * @param conceptMapType the concept map type object to unretire
   * @return the url to redirect to
   */
  @RequestMapping(method = RequestMethod.POST, value = "/admin/concepts/unretireConceptMapType")
  public String unretireConceptMapType(
      WebRequest request, @ModelAttribute(value = "conceptMapType") ConceptMapType conceptMapType) {

    try {
      Context.getConceptService().unretireConceptMapType(conceptMapType);
      if (log.isDebugEnabled()) {
        log.debug("Unretired concept map type with id: " + conceptMapType.getId());
      }
      request.setAttribute(
          WebConstants.OPENMRS_MSG_ATTR,
          Context.getMessageSourceService().getMessage("ConceptMapType.unretired"),
          WebRequest.SCOPE_SESSION);

      return "redirect:" + CONCEPT_MAP_TYPE_LIST_URL + ".list";
    } catch (APIException e) {
      log.error("Error occurred while attempting to unretire concept map type", e);
      request.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR,
          Context.getMessageSourceService().getMessage("ConceptMapType.unretire.error"),
          WebRequest.SCOPE_SESSION);
    }

    // an error occurred
    return CONCEPT_MAP_TYPE_FORM;
  }
  @RequestMapping("/module/hirifxray/participant.form")
  public String viewParticipant(
      ModelMap model,
      @RequestParam(value = "id", required = true) Integer id,
      @RequestParam(value = "type", required = false) Concept type,
      @RequestParam(value = "xrayId", required = false) Encounter encounter) {

    User currentUser = Context.getAuthenticatedUser();
    if (currentUser == null) {
      return "redirect:/login.htm";
    }

    Xray xray = new Xray(encounter);

    model.addAttribute("type", type);
    model.addAttribute("xray", xray);

    Patient patient = Context.getPatientService().getPatient(id);
    model.addAttribute("patient", patient);

    model.addAttribute("xrayTypes", HirifMetadata.getXrayTypes());
    model.addAttribute("xraysByType", HirifUtil.getXraysByType(patient));

    model.addAttribute("xrayLocations", HirifMetadata.getXrayLocations());

    model.addAttribute("xrayStatuses", HirifMetadata.getXrayStatuses());
    model.addAttribute("notDoneStatus", HirifMetadata.getNotDoneStatus());
    model.addAttribute("completedStatus", HirifMetadata.getCompletedStatus());

    return null;
  }
  /**
   * Refresh the local cache of Flags by loading all enabled Flags from the database Also refresh
   * the privilege cache Note that flags and tags must be eagerly loaded for this to work
   */
  private void refreshCache() {
    // get the enabled flags and all tags for the flag and tag caches
    flagCache = dao.getAllEnabledFlags();
    tagCache = getAllTags();

    // alphabetize the flags, and sort by by priority ranking so that result sets are returned that
    // way
    Collections.sort(flagCache, new FlagAlphaComparator());
    Collections.sort(flagCache, new FlagPriorityComparator());

    // get the privileges associate with the patient flags default user for the privileges cache
    try {
      Context.addProxyPrivilege("View Users");
      String username =
          Context.getAdministrationService().getGlobalProperty("patientflags.username");
      User user = Context.getUserService().getUserByUsername(username);

      if (user != null) {
        if (user.isSuperUser()) { // need to explicitly get all privileges if user is a super user
          privilegeCache = Context.getUserService().getAllPrivileges();
        } else {
          privilegeCache = user.getPrivileges();
        }
      } else {
        privilegeCache = null;
      }
    } finally {
      Context.removeProxyPrivilege("View Users");
    }

    // set the initialized flag to true
    isInitialized = true;
  }
  @Test
  public void should_fail_to_persist_if_conceptSetRow_introduces_cycle() throws Exception {
    ConceptSetRow row1 = new ConceptSetRow();
    row1.name = "ConceptA";
    row1.conceptClass = "New Class";
    row1.description = "some description";
    List<KeyValue> children = new ArrayList<>();
    children.add(new KeyValue("1", "Child1"));
    children.add(new KeyValue("2", "Child2"));
    row1.children = children;

    Messages persistErrorMessages = conceptSetPersister.persist(row1);
    assertTrue(persistErrorMessages.isEmpty());
    Context.openSession();
    Context.authenticate("admin", "test");
    Concept persistedConcept = conceptService.getConceptByName(row1.name);
    assertNotNull(persistedConcept);

    ConceptSetRow row2 = new ConceptSetRow();
    row2.name = "Child2";
    row2.conceptClass = "New Class";
    row2.description = "some description";
    List<KeyValue> children1 = new ArrayList<>();
    children1.add(new KeyValue("1", "ConceptA"));
    children1.add(new KeyValue("2", "Child3"));
    row2.children = children1;

    Messages persistErrorMessages1 = conceptSetPersister.persist(row2);
    assertFalse(persistErrorMessages1.isEmpty());

    Context.flushSession();
    Context.closeSession();
  }
Example #23
0
  /**
   * @return string representation of the result. For non-text results, this will either be the
   *     overridden text value (if specifically defined) or a string representation of the default
   *     datatype value. If the result is a list, then the string representation of all members a
   *     joined with commas.
   */
  public String toString() {
    if (isSingleResult()) {
      if (datatype == null) {
        return valueText == null ? "" : valueText;
      }

      switch (datatype) {
        case BOOLEAN:
          return (valueBoolean ? "true" : "false");
        case CODED:
          return (valueCoded == null ? "" : valueCoded.getBestName(Context.getLocale()).getName());
        case DATETIME:
          return (valueDatetime == null ? "" : Context.getDateFormat().format(valueDatetime));
        case NUMERIC:
          return (valueNumeric == null ? "" : String.valueOf(valueNumeric));
        case TEXT:
          return (valueText == null ? "" : valueText);
        default:
          return valueText;
      }
    }
    StringBuffer s = new StringBuffer();
    for (Result r : this) {
      if (s.length() > 0) {
        s.append(",");
      }
      s.append(r.toString());
    }
    return s.toString();
  }
  @Test
  public void addSetMembers() throws Exception {
    ConceptSetRow conceptRow = new ConceptSetRow();
    conceptRow.name = "New concept";
    conceptRow.conceptClass = "New Class";
    conceptRow.description = "some description";

    List<KeyValue> children = new ArrayList<>();
    children.add(new KeyValue("1", "Child1"));
    children.add(new KeyValue("2", "Child2"));
    conceptRow.children = children;
    Messages persistErrorMessages = conceptSetPersister.persist(conceptRow);
    assertTrue(persistErrorMessages.isEmpty());
    Context.openSession();
    Context.authenticate("admin", "test");
    Concept persistedConcept = conceptService.getConceptByName(conceptRow.name);
    assertNotNull(persistedConcept);
    assertEquals(conceptRow.name, persistedConcept.getName(Context.getLocale()).getName());
    assertEquals(conceptRow.conceptClass, persistedConcept.getConceptClass().getName());
    assertEquals("some description", persistedConcept.getDescription().getDescription());

    assertEquals(2, persistedConcept.getSetMembers().size());
    assertEquals("some description", persistedConcept.getDescription().getDescription());
    assertEquals(0, persistedConcept.getSynonyms().size());
    assertTrue(persistedConcept.isSet());
    Context.flushSession();
    Context.closeSession();
  }
 private DicomObject doNCreate(DicomObject rq, DicomObject data, DicomObject rsp)
     throws DicomServiceException {
   String iuid = rq.getString(Tag.AffectedSOPInstanceUID);
   if (iuid == null) iuid = rsp.getString(Tag.AffectedSOPInstanceUID);
   File f = mkFile(iuid);
   if (f.exists()) {
     throw new DicomServiceException(rq, Status.DuplicateSOPinstance);
   }
   data.initFileMetaInformation(
       UID.ModalityPerformedProcedureStepSOPClass, iuid, UID.ExplicitVRLittleEndian);
   try {
     store(f, data);
     try {
       Context.openSession();
       DicomUtils.updateStudyPerformedStatusByMpps(data);
     } catch (Exception e) {
       debug("Can not update database with");
       debug(data.toString());
       e.printStackTrace();
     } finally {
       Context.closeSession();
     }
   } catch (Exception e) {
     throw new DicomServiceException(rq, Status.ProcessingFailure);
   }
   return null;
 }
 /**
  * Creates a new person stub.
  *
  * @param given
  * @param middle
  * @param family
  * @param birthdate
  * @param dateformat
  * @param age
  * @param gender
  * @return PersonListItem person stub created
  */
 public Object createPerson(
     String given,
     String middle,
     String family,
     String birthdate,
     String dateformat,
     String age,
     String gender) {
   log.error(
       given
           + " "
           + middle
           + " "
           + family
           + " "
           + birthdate
           + " "
           + dateformat
           + " "
           + age
           + " "
           + gender);
   User user = Context.getAuthenticatedUser();
   Person p = new Person();
   p.setPersonCreator(user);
   p.setPersonDateCreated(new Date());
   p.setPersonChangedBy(user);
   p.setPersonDateChanged(new Date());
   if (StringUtils.isEmpty(gender)) {
     log.error("Gender cannot be null.");
     return String.valueOf("Gender cannot be null.");
   } else if (gender.toUpperCase().contains("M")) {
     p.setGender("M");
   } else if (gender.toUpperCase().contains("F")) {
     p.setGender("F");
   } else {
     log.error("Gender must be 'M' or 'F'.");
     return new String("Gender must be 'M' or 'F'.");
   }
   if ("".equals(given) || "".equals(family)) {
     log.error("Given name and family name cannot be null.");
     return new String("Given name and family name cannot be null.");
   }
   PersonName name = new PersonName(given, middle, family);
   name.setCreator(user);
   name.setDateCreated(new Date());
   name.setChangedBy(user);
   name.setDateChanged(new Date());
   p.addName(name);
   try {
     Date d = updateAge(birthdate, dateformat, age);
     p.setBirthdate(d);
   } catch (java.text.ParseException pe) {
     log.error(pe);
     return new String("Birthdate cannot be parsed.");
   }
   p.setGender(gender);
   Person person = Context.getPersonService().savePerson(p);
   return PersonListItem.createBestMatch(person);
 }
  /**
   * Processes requests to unretire concept reference terms
   *
   * @param request the {@link WebRequest} object
   * @param conceptReferenceTermModel the concept reference term model object for the term to
   *     unretire
   * @param retireReason the reason why the concept reference term is being unretired
   * @return the url to redirect to
   */
  @RequestMapping(
      method = RequestMethod.POST,
      value = "/admin/concepts/unretireConceptReferenceTerm")
  public String unretireConceptReferenceTerm(
      WebRequest request,
      @ModelAttribute(value = "conceptReferenceTermModel")
          ConceptReferenceTermModel conceptReferenceTermModel) {

    try {
      ConceptReferenceTerm conceptReferenceTerm =
          conceptReferenceTermModel.getConceptReferenceTerm();
      Context.getConceptService().unretireConceptReferenceTerm(conceptReferenceTerm);
      if (log.isDebugEnabled()) {
        log.debug("Unretired concept reference term with id: " + conceptReferenceTerm.getId());
      }
      request.setAttribute(
          WebConstants.OPENMRS_MSG_ATTR,
          Context.getMessageSourceService().getMessage("ConceptReferenceTerm.unretired"),
          WebRequest.SCOPE_SESSION);

      return "redirect:"
          + CONCEPT_REFERENCE_TERM_FORM_URL
          + ".form?conceptReferenceTermId="
          + conceptReferenceTerm.getConceptReferenceTermId();
    } catch (APIException e) {
      log.error("Error occurred while unretiring concept reference term", e);
      request.setAttribute(
          WebConstants.OPENMRS_ERROR_ATTR,
          Context.getMessageSourceService().getMessage("ConceptReferenceTerm.unretire.error"),
          WebRequest.SCOPE_SESSION);
    }

    // an error occurred, show the form
    return CONCEPT_REFERENCE_TERM_FORM;
  }
  /** @see org.openmrs.api.EncounterService#unvoidEncounter(org.openmrs.Encounter) */
  public Encounter unvoidEncounter(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.unvoid",
          new Object[] {encounter.getEncounterType().getEditPrivilege()});
    }

    String voidReason = encounter.getVoidReason();
    if (voidReason == null) {
      voidReason = "";
    }

    ObsService os = Context.getObsService();
    for (Obs o : encounter.getObsAtTopLevel(true)) {
      if (voidReason.equals(o.getVoidReason())) {
        os.unvoidObs(o);
      }
    }

    OrderService orderService = Context.getOrderService();
    for (Order o : encounter.getOrders()) {
      if (voidReason.equals(o.getVoidReason())) {
        orderService.unvoidOrder(o);
      }
    }

    encounter.setVoided(false);
    encounter.setVoidedBy(null);
    encounter.setDateVoided(null);
    encounter.setVoidReason(null);
    Context.getEncounterService().saveEncounter(encounter);
    return encounter;
  }
  /**
   * @see
   *     org.springframework.web.servlet.mvc.SimpleFormController#referenceData(javax.servlet.http.HttpServletRequest,
   *     java.lang.Object, org.springframework.validation.Errors)
   */
  protected Map<String, Object> referenceData(HttpServletRequest request, Object obj, Errors errs)
      throws Exception {

    Drug drug = (Drug) obj;

    Map<String, Object> map = new HashMap<String, Object>();
    String defaultVerbose = "false";

    if (Context.isAuthenticated()) {
      if (drug.getConcept() != null)
        map.put("conceptName", drug.getConcept().getName(request.getLocale()));
      defaultVerbose =
          Context.getAuthenticatedUser()
              .getUserProperty(OpenmrsConstants.USER_PROPERTY_SHOW_VERBOSE);
    }

    map.put("defaultVerbose", defaultVerbose.equals("true") ? true : false);

    String editReason = request.getParameter("editReason");
    if (editReason == null) editReason = "";

    map.put("editReason", editReason);

    return map;
  }
  /** @see {@link OrderValidator#validate(Object,Errors)} */
  @Test
  @Verifies(
      value = "should pass validation if all fields are correct",
      method = "validate(Object,Errors)")
  public void validate_shouldPassValidationIfAllFieldsAreCorrect() throws Exception {
    Order order = new DrugOrder();
    Encounter encounter = new Encounter();
    order.setConcept(Context.getConceptService().getConcept(88));
    order.setOrderer(Context.getProviderService().getProvider(1));
    Patient patient = Context.getPatientService().getPatient(2);
    encounter.setPatient(patient);
    order.setPatient(patient);
    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH) - 1);
    order.setDateActivated(cal.getTime());
    order.setAutoExpireDate(new Date());
    order.setCareSetting(new CareSetting());
    order.setEncounter(encounter);
    order.setUrgency(Order.Urgency.ROUTINE);
    order.setAction(Order.Action.NEW);
    order.setOrderType(Context.getOrderService().getOrderTypeByName("Drug order"));

    Errors errors = new BindException(order, "order");
    new OrderValidator().validate(order, errors);

    Assert.assertFalse(errors.hasErrors());
  }