/**
   * @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());
  }
  /** @should return patient data for each obs in the passed context */
  @Override
  public EvaluatedObsData evaluate(
      ObsDataDefinition definition, EvaluationContext obsEvaluationContext)
      throws EvaluationException {

    DataSetQueryService dqs = Context.getService(DataSetQueryService.class);
    EvaluatedObsData c = new EvaluatedObsData(definition, obsEvaluationContext);

    // create a map of obs ids -> patient ids (note assumption that personId = patientId)
    Set<Integer> obsIds = ObsDataUtil.getObsIdsForContext(obsEvaluationContext, true);
    Map<Integer, Integer> convertedIds =
        dqs.convertData(Person.class, "personId", null, Obs.class, "person.personId", obsIds);

    // create a new (patient) evaluation context using the retrieved ids
    EvaluationContext patientEvaluationContext = new EvaluationContext();
    patientEvaluationContext.setBaseCohort(new Cohort(convertedIds.values()));

    // evaluate the joined definition via this patient context
    PatientToObsDataDefinition def = (PatientToObsDataDefinition) definition;
    EvaluatedPatientData pd =
        Context.getService(PatientDataService.class)
            .evaluate(def.getJoinedDefinition(), patientEvaluationContext);

    // now create the result set by mapping the results in the patient data set to obs ids
    for (Integer obsId : obsIds) {
      c.addData(obsId, pd.getData().get(convertedIds.get(obsId)));
    }
    return c;
  }
  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 LabCatalogService#purgeLabTest(LabTest)
   * @verifies delete given LabTest
   */
  @Test
  public void purgeLabTest_shouldDeleteGivenLabTest() throws Exception {
    String uuid = "5d1545bb-486e-11e1-b5ed-0024e8c61285";

    LabTest labTest = Context.getService(LabCatalogService.class).getLabTestByUUID(uuid);
    Context.getService(LabCatalogService.class).purgeLabTest(labTest);

    labTest = Context.getService(LabCatalogService.class).getLabTestByUUID(uuid);
    Assert.assertNull("purgeLabTest should return null", labTest);
  }
 /**
  * @see purgeLabSpecimenTemplate(LabSpecimenTemplate labSpecimenTemplate)
  * @verifies purge LabSpecimenTemplate
  */
 @Test
 @SkipBaseSetup
 public void purgeLabSpecimenTemplate_shouldPurgeLabSpecimenTemplate() throws Exception {
   LabSpecimenTemplate labSpecimenTemplate =
       Context.getService(LabCatalogService.class)
           .getLabSpecimenTemplateByUuid("35442792-49b7-11e1-812a-0024e8c61285");
   Context.getService(LabCatalogService.class).purgeLabSpecimenTemplate(labSpecimenTemplate);
   labSpecimenTemplate =
       Context.getService(LabCatalogService.class)
           .getLabSpecimenTemplateByUuid("35442792-49b7-11e1-812a-0024e8c61285");
   Assert.assertNull("purgeLabSpecimenTemplate should return null", labSpecimenTemplate);
 }
 /**
  * @see purgeLabPrecondition(LabPrecondition labLabPrecondition)
  * @verifies purge LabPrecondition
  */
 @Test
 @SkipBaseSetup
 public void purgeLabPrecondition_shouldPurgeLabPrecondition() throws Exception {
   LabPrecondition labPrecondition =
       Context.getService(LabCatalogService.class)
           .getLabPreconditionByUuid("0100dc0a-46da-11e1-99f4-0024e8c61285");
   Context.getService(LabCatalogService.class).purgeLabPrecondition(labPrecondition);
   labPrecondition =
       Context.getService(LabCatalogService.class)
           .getLabPreconditionByUuid("0100dc0a-46da-11e1-99f4-0024e8c61285");
   Assert.assertNull("purgeLabPrecondition should return null", labPrecondition);
 }
Example #7
0
  /** @see {@link LogicService#findToken(String)} */
  @Test
  @Verifies(
      value = "should return all registered token matching the input partially",
      method = "getTokens(String)")
  public void getTokens_shouldReturnAllRegisteredTokenMatchingTheInputPartially() throws Exception {
    LogicService logicService = Context.getLogicService();

    Context.getService(TokenService.class)
        .registerToken("One Another", new ClassRuleProvider(), "one");
    Context.getService(TokenService.class)
        .registerToken("Two Another", new ClassRuleProvider(), "two");

    List<String> tokens = logicService.getTokens("ANOTHER");
    Assert.assertEquals(2, tokens.size());
  }
 @Test(expected = APIException.class)
 @SkipBaseSetup
 public void saveLabPrecondition_shouldFailIfRequiredFieldsAreMissing() throws Exception {
   LabPrecondition labPrecondition = new LabPrecondition();
   Context.getService(LabCatalogService.class).saveLabPrecondition(labPrecondition);
   Assert.assertNotNull("saveLabPrecondition should fail if required fields are missing", null);
 }
  @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
  }
  /** @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);
  }
  /**
   * 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;
  }
  public PatientDataResult evaluate(RowPerPatientData patientData, EvaluationContext context)
      throws EvaluationException {

    CustomCalculationBasedOnMultiplePatientDataDefinitions pd =
        (CustomCalculationBasedOnMultiplePatientDataDefinitions) patientData;

    List<Mapped<RowPerPatientData>> definitions = pd.getPatientDataToBeEvaluated();
    List<PatientDataResult> results = new ArrayList<PatientDataResult>();

    for (Mapped<RowPerPatientData> def : definitions) {
      RowPerPatientData data = def.getParameterizable();
      data.setPatient(pd.getPatient());
      data.setPatientId(pd.getPatientId());
      def.setParameterizable(data);

      PatientDataResult patientDataResult =
          Context.getService(RowPerPatientDataService.class).evaluate(def, context);
      results.add(patientDataResult);
    }

    if (pd.getCalculator() != null) {
      PatientDataResult result = pd.getCalculator().calculateResult(results, context);
      result.setDefinition(patientData.getDescription());
      result.setName(patientData.getName());
      result.setEc(context);
      result.setPatientData(patientData);
      return result;
    }

    return new NullResult(pd, context);
  }
  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);
  }
 /**
  * @see retireLabSpecimenTemplate(LabSpecimenTemplate labSpecimenTemplate, String reason)
  * @verifies retire LabSpecimenTemplate
  */
 @Test
 @SkipBaseSetup
 public void retireLabSpecimenTemplate_shouldRetireLabSpecimenTemplate() throws Exception {
   LabSpecimenTemplate labSpecimenTemplate =
       Context.getService(LabCatalogService.class)
           .getLabSpecimenTemplateByUuid("35442792-49b7-11e1-812a-0024e8c61285");
   Context.getService(LabCatalogService.class).retireLabSpecimenTemplate(labSpecimenTemplate, "");
   labSpecimenTemplate =
       Context.getService(LabCatalogService.class)
           .getLabSpecimenTemplateByUuid("35442792-49b7-11e1-812a-0024e8c61285");
   Assert.assertNotNull("retireLabSpecimenTemplate should not return null", labSpecimenTemplate);
   Assert.assertEquals(
       "retireLabSpecimenTemplate should return the right object with voided true",
       "true",
       labSpecimenTemplate.getRetired().toString());
 }
 /**
  * @see voidLabPrecondition(LabPrecondition labLabPrecondition, String reason)
  * @verifies void LabPrecondition
  */
 @Test
 @SkipBaseSetup
 public void voidLabPrecondition_shouldVoidedLabPrecondition() throws Exception {
   LabPrecondition labPrecondition =
       Context.getService(LabCatalogService.class)
           .getLabPreconditionByUuid("0100dc0a-46da-11e1-99f4-0024e8c61285");
   Context.getService(LabCatalogService.class).voidLabPrecondition(labPrecondition, "");
   labPrecondition =
       Context.getService(LabCatalogService.class)
           .getLabPreconditionByUuid("0100dc0a-46da-11e1-99f4-0024e8c61285");
   Assert.assertNotNull("voidLabPrecondition should not return null", labPrecondition);
   Assert.assertEquals(
       "voidLabPrecondition should return the right object with voided true",
       "true",
       labPrecondition.getVoided().toString());
 }
  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);
  }
 @Override
 protected PageableResult doGetAll(RequestContext context) {
   return new NeedsPaging<LabSpecimenTemplate>(
       Context.getService(LabCatalogService.class)
           .getLabSpecimenTemplate("", context.getIncludeAll(), null, null),
       context);
 }
 @Override
 protected void populateModel(HttpServletRequest request, Map<String, Object> model) {
   super.populateModel(request, model);
   List<DefinitionSummary> definitionSummaries =
       Context.getService(ReportDefinitionService.class).getAllDefinitionSummaries(false);
   model.put("definitionSummaries", definitionSummaries);
 }
  /**
   * @see org.springframework.validation.Validator#validate(java.lang.Object,
   *     org.springframework.validation.Errors)
   */
  public void validate(Object command, Errors error) {
    InventoryStore store = (InventoryStore) command;

    if (StringUtils.isBlank(store.getName())) {
      error.reject("inventory.store.name.required");
    }
    if (store.getRole() == null) {
      error.reject("inventory.store.role.required");
    }
    /*if( StringUtils.isBlank(store.getCode())){
    	error.reject("inventory.store.code.required");
    }*/
    InventoryService inventoryService =
        (InventoryService) Context.getService(InventoryService.class);
    InventoryStore storeE = inventoryService.getStoreByName(store.getName());
    if (store.getId() != null) {
      if (storeE != null && storeE.getId().intValue() != store.getId().intValue()) {
        error.reject("inventory.store.name.existed");
      }
    } else {
      if (storeE != null) {
        error.reject("inventory.store.name.existed");
      }
    }
  }
 /**
  * @see LabCatalogService#getAllLabTestPanels()
  * @verifies get all LabTestPanel
  */
 @Test
 public void getAllLabTestPanels_shouldGetAllLabTestPanel() throws Exception {
   List<LabTestPanel> list =
       Context.getService(LabCatalogService.class).getAllLabTestPanels(false);
   Assert.assertNotNull("getAllLabTestPanels should not return null", list);
   Assert.assertEquals("getAllLabTestPanels should return the right objects", 5, list.size());
 }
  @RequestMapping(method = RequestMethod.GET)
  public String main(
      //			@RequestParam(value = "date", required = false) String dateStr,
      @RequestParam(value = "searchKey", required = false) String searchKey,
      @RequestParam(value = "currentPage", required = false) Integer currentPage,
      // 21/11/2014 to work with size selector
      @RequestParam(value = "pgSize", required = false) Integer pgSize,
      Model model) {

    IpdService ipdService = (IpdService) Context.getService(IpdService.class);
    /*	SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    		Date date = null;
    		try {
    			date = sdf.parse(dateStr);
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    */
    //		List<IpdPatientAdmission> listIndoorPatient1 = ipdService.getAllIndoorPatient();
    // 24/11/2014 to Work with size selctor for IPDQueue
    List<IpdPatientAdmissionLog> listIndoorPatient2 =
        ipdService.getAllIndoorPatientFromAdmissionLog(searchKey, currentPage, pgSize);

    if (currentPage == null) currentPage = 1;

    int total = ipdService.countGetAllIndoorPatientFromAdmissionLog(searchKey, currentPage);
    PagingUtil pagingUtil = new PagingUtil(pgSize, currentPage, total);

    //		model.addAttribute("listIndoorPatient1", listIndoorPatient1);
    model.addAttribute("listIndoorPatient2", listIndoorPatient2);
    model.addAttribute("pagingUtil", pagingUtil);
    //	model.addAttribute("date", dateStr);
    return "/module/billing/indoorQueue/indoorBillingQueue";
  }
 public List<Practitioner> searchByName(StringParam name) {
   org.openmrs.module.fhir.api.PractitionerService patientService =
       Context.getService( // the reference is wrong :)
           org.openmrs.module.fhir.api.PractitionerService.class);
   return patientService.searchPractitionersByName(
       name.getValue()); // IS THIS SHOUDL BE PATIENT SERVICE?????????????
 }
  /**
   * Auto generated method comment
   *
   * @param from
   * @param to
   * @param locationId
   * @return
   */
  public static String getNumberOfCouplesCounseledAndTested(
      String from, String to, Integer locationId, Integer whoGetTested) {
    VCTModuleService vms = Context.getService(VCTModuleService.class);
    Integer res = vms.getNumberOfCouplesCounseledAndTested(from, to, locationId, whoGetTested);

    return (res != null) ? "" + res : "-";
  }
  /** @should return person data for each obs in the passed context */
  @Override
  public EvaluatedObsData evaluate(ObsDataDefinition definition, EvaluationContext context)
      throws EvaluationException {

    EvaluatedObsData c = new EvaluatedObsData(definition, context);

    // create a map of obs ids -> patient ids

    HqlQueryBuilder q = new HqlQueryBuilder();
    q.select("o.obsId", "o.personId");
    q.from(Obs.class, "o");
    q.whereObsIn("o.obsId", context);

    Map<Integer, Integer> convertedIds =
        evaluationService.evaluateToMap(q, Integer.class, Integer.class, context);

    if (!convertedIds.keySet().isEmpty()) {
      // create a new (person) evaluation context using the retrieved ids
      PersonEvaluationContext personEvaluationContext = new PersonEvaluationContext();
      personEvaluationContext.setBasePersons(
          new PersonIdSet(new HashSet<Integer>(convertedIds.values())));

      // evaluate the joined definition via this person context
      PersonToObsDataDefinition def = (PersonToObsDataDefinition) definition;
      EvaluatedPersonData pd =
          Context.getService(PersonDataService.class)
              .evaluate(def.getJoinedDefinition(), personEvaluationContext);

      // now create the result set by mapping the results in the person data set to obs ids
      for (Integer obsId : convertedIds.keySet()) {
        c.addData(obsId, pd.getData().get(convertedIds.get(obsId)));
      }
    }
    return c;
  }
  public void validate(Object target, Errors errors) {
    Tag targetTag = (Tag) target;
    FlagService flagService = Context.getService(FlagService.class);

    // name and criteria cannot be empty
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "patientflags.errors.noTag");

    // make sure that the tag field isn't too large
    if (targetTag.getName().length() > 255)
      errors.rejectValue("name", "patientflags.errors.tagTooLong");

    // if this is a new tag, make sure that a tag with the same name doesn't already exist
    // TODO this doesn't stop you from changing the name of tag to the identical name of another tag
    if (targetTag.getId() == null) {
      List<Tag> tags = flagService.getAllTags();
      if (tags != null) {
        for (Tag tag : tags) {
          if (tag.getName().equalsIgnoreCase(targetTag.getName())) {
            errors.rejectValue("tag", "patientflags.errors.tagNameExists");
            break;
          }
        }
      }
    }
  }
  /** @see Moh731CohortLibrary#currentlyInCare() */
  @Test
  public void currentlyInCare() throws Exception {
    EncounterType triage = MetadataUtils.getEncounterType(CommonMetadata._EncounterType.TRIAGE);
    EncounterType hivConsult =
        MetadataUtils.getEncounterType(HivMetadata._EncounterType.HIV_CONSULTATION);

    // Give patient #2 irrelevant encounter during 90 day window
    TestUtils.saveEncounter(TestUtils.getPatient(2), triage, TestUtils.date(2012, 6, 15));

    // Give patient #6 relevant encounter before and after 90 day window
    TestUtils.saveEncounter(TestUtils.getPatient(6), hivConsult, TestUtils.date(2012, 3, 31));
    TestUtils.saveEncounter(TestUtils.getPatient(6), hivConsult, TestUtils.date(2012, 7, 1));

    // Give patient #7 relevant encounter at start of 90 day window
    TestUtils.saveEncounter(TestUtils.getPatient(7), hivConsult, TestUtils.date(2012, 4, 1));

    // Give patient #8 relevant encounter at end of 90 day window
    TestUtils.saveEncounter(TestUtils.getPatient(8), hivConsult, TestUtils.date(2012, 6, 30));

    CohortDefinition cd = moh731Cohorts.currentlyInCare();
    context.addParameterValue("onDate", PERIOD_END);
    EvaluatedCohort evaluated =
        Context.getService(CohortDefinitionService.class).evaluate(cd, context);
    ReportingTestUtils.assertCohortEquals(Arrays.asList(7, 8), evaluated);
  }
  @RequestMapping(method = RequestMethod.GET)
  public String displayForm(
      @ModelAttribute("command") Object command,
      @RequestParam("billId") Integer billId,
      HttpServletRequest request,
      Model model) {

    BillingService billingService = (BillingService) Context.getService(BillingService.class);

    List<MiscellaneousService> listMiscellaneousService =
        billingService.getAllMiscellaneousService();

    if (listMiscellaneousService == null || listMiscellaneousService.size() == 0) {
      request
          .getSession()
          .setAttribute(WebConstants.OPENMRS_MSG_ATTR, "No MiscellaneousService found.");
    } else {
      model.addAttribute("listMiscellaneousService", listMiscellaneousService);
    }

    MiscellaneousServiceBill bill = billingService.getMiscellaneousServiceBillById(billId);
    model.addAttribute("bill", bill);

    return "module/billing/main/miscellaneousServiceBillEdit";
  }
  /**
   * @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());
  }
  // Can't get this to work... again the annoying "HttpMediaTypeNotSupportedException: Content type
  // 'application/json' not supported"
  @Test
  @Ignore
  public void
      updateProposal_UpdatedPackageIsToBeSubmittedWhileExistingIsDraft_ShouldMakeRestCallAndPersistWithStatusSubmitted()
          throws Exception {

    final ProposedConceptPackage proposedConcept = new ProposedConceptPackage();
    proposedConcept.setStatus(PackageStatus.DRAFT);

    final ProposedConceptService cpServiceMock = mock(ProposedConceptService.class);
    when(cpServiceMock.getProposedConceptPackageById(1)).thenReturn(proposedConcept);

    mockStatic(Context.class);
    when(Context.getService(ProposedConceptService.class)).thenReturn(cpServiceMock);

    final RestOperations restOperationsMock = mock(RestOperations.class);
    ReflectionTestUtils.setField(
        controller.getSubmitProposal(), "submissionRestTemplate", restOperationsMock);

    request = new MockHttpServletRequest("PUT", "/cpm/proposals/1");
    request.addHeader("Accept", "application/json");
    request.addHeader("Content-Type", "application/json");
    final String payload =
        "{\"name\":\"test\",\"description\":\"test\",\"email\":\"[email protected]\",\"concepts\":[]}";
    request.setContent(payload.getBytes());

    adapter.handle(request, response, controller);

    verify(restOperationsMock)
        .postForObject(
            "http://localhost:8080/openmrs/ws/cpm/dictionarymanager/proposals",
            new SubmissionDto(),
            SubmissionResponseDto.class);
    assertThat(proposedConcept.getStatus(), equalTo(PackageStatus.SUBMITTED));
  }
 @Test(expected = APIException.class)
 @SkipBaseSetup
 public void saveLabPrecondition_shouldFailIfNull() throws Exception {
   LabPrecondition labPrecondition = null;
   Context.getService(LabCatalogService.class).saveLabPrecondition(labPrecondition);
   Assert.assertNotNull("saveLabPrecondition should fail if null", null);
 }