@Test
  public void testSimplify() throws Exception {
    PersonName name = new PersonName();
    name.setGivenName("Barack");
    name.setFamilyName("Obama");

    PatientIdentifierType pit = new PatientIdentifierType();
    pit.setName("US President Number");

    Patient patient = new Patient();
    patient.setPatientId(44);
    patient.addName(name);
    patient.setGender("M");
    patient.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse("1961-08-04"));
    patient.addIdentifier(new PatientIdentifier("44", pit, new Location()));

    EmrApiProperties emrApiProperties = mock(EmrApiProperties.class);
    when(emrApiProperties.getPrimaryIdentifierType()).thenReturn(pit);

    TestUiUtils ui = new TestUiUtils();
    SimpleObject o = new FindPatientFragmentController().simplify(ui, emrApiProperties, patient);

    assertEquals("Barack", PropertyUtils.getProperty(o, "preferredName.givenName"));
    assertNull(PropertyUtils.getProperty(o, "preferredName.middleName"));
    assertEquals("Obama", PropertyUtils.getProperty(o, "preferredName.familyName"));
    assertEquals("Barack Obama", PropertyUtils.getProperty(o, "preferredName.fullName"));
    assertEquals("04.Aug.1961", PropertyUtils.getProperty(o, "birthdate"));
    assertEquals(Boolean.FALSE, PropertyUtils.getProperty(o, "birthdateEstimated"));
    assertEquals("M", PropertyUtils.getProperty(o, "gender"));

    Object primaryIdentifier = ((List) o.get("primaryIdentifiers")).get(0);
    assertThat((String) PropertyUtils.getProperty(primaryIdentifier, "identifier"), is("44"));
  }
 /** @see org.openmrs.module.kenyaui.simplifier.AbstractSimplifier#simplify(Object) */
 @Override
 protected SimpleObject simplify(VisitType visitType) {
   SimpleObject ret = new SimpleObject();
   ret.put("id", visitType.getId());
   ret.put("name", visitType.getName());
   ret.put("description", visitType.getDescription());
   return ret;
 }
  @Test
  public void testParsingDispositionWithTransferLocation() throws Exception {
    Concept admit =
        new ConceptBuilder(
                null,
                conceptService.getConceptDatatypeByName("N/A"),
                conceptService.getConceptClassByName("Misc"))
            .addName("Transfer")
            .get();
    when(emrConceptService.getConcept("test:transfer")).thenReturn(admit);

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

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

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

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

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

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

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

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

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

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

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

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

    assertThat(parsed.getDiagnoses().size(), is(0));
    assertThat(parsed.getDispositions().size(), is(1));
    assertThat(parsed.getObs().size(), is(0));
    assertThat(path(parsed.getDispositions(), 0, "disposition"), is((Object) "Death"));
    assertThat(
        path(parsed.getDispositions(), 0, "additionalObs"), is((Object) expectedAdditionalObsList));
  }
  /** Validate patient records */
  @AppAction(EmrConstants.APP_DEVELOPER)
  public List<SimpleObject> validatePatients(UiUtils ui) {
    List<SimpleObject> problems = new ArrayList<SimpleObject>();

    for (Patient patient : Context.getPatientService().getAllPatients()) {
      BindException errors = new BindException(patient, "");
      Context.getAdministrationService().validate(patient, errors);

      if (errors.hasErrors()) {
        SimpleObject problem = new SimpleObject();
        problem.put("patient", ui.simplifyObject(patient));
        problem.put("errors", uniqueErrorMessages(errors));
        problem.put("cause", errors.getCause());
        problems.add(problem);
      }
    }

    return problems;
  }
  SimpleObject simplify(UiUtils ui, EmrApiProperties emrApiProperties, Patient patient) {
    PersonName name = patient.getPersonName();
    SimpleObject preferredName =
        SimpleObject.fromObject(name, ui, "givenName", "middleName", "familyName", "familyName2");
    preferredName.put("name", ui.format(name));

    PatientIdentifierType primaryIdentifierType = emrApiProperties.getPrimaryIdentifierType();
    List<PatientIdentifier> primaryIdentifiers =
        patient.getPatientIdentifiers(primaryIdentifierType);

    SimpleObject o =
        SimpleObject.fromObject(
            patient, ui, "patientId", "gender", "age", "birthdate", "birthdateEstimated");
    o.put("preferredName", preferredName);
    o.put("primaryIdentifiers", SimpleObject.fromCollection(primaryIdentifiers, ui, "identifier"));

    return o;
  }
  public void controller(
      @RequestParam(value = "patientId", required = false) Patient patient,
      @RequestParam(value = "headerForm") String headerForm,
      @RequestParam(value = "flowsheets") String[] flowsheets,
      @RequestParam(value = "viewOnly", required = false) Boolean viewOnly,
      @RequestParam(value = "requireEncounter", required = false) Boolean requireEncounter,
      UiUtils ui,
      PageModel model,
      @SpringBean("htmlFormEntryService") HtmlFormEntryService htmlFormEntryService,
      @SpringBean("formService") FormService formService,
      @SpringBean("locationService") LocationService locationService,
      @SpringBean("coreResourceFactory") ResourceFactory resourceFactory,
      @InjectBeans PatientDomainWrapper patientDomainWrapper,
      PageRequest pageRequest) {

    patientDomainWrapper.setPatient(patient);
    model.addAttribute("patient", patientDomainWrapper);
    model.addAttribute("headerForm", headerForm);
    model.addAttribute("flowsheets", flowsheets);
    model.addAttribute("requireEncounter", (requireEncounter == null || requireEncounter));

    Location defaultLocation = null;
    Integer locationId =
        pageRequest
            .getSession()
            .getAttribute(PihMalawiWebConstants.SESSION_LOCATION_ID, Integer.TYPE);
    if (locationId != null) {
      defaultLocation = locationService.getLocation(locationId);
    }

    List<Encounter> allEncounters = new ArrayList<Encounter>();

    List<String> alerts = new ArrayList<String>();

    String headerFormResource = "pihmalawi:htmlforms/" + headerForm + ".xml";

    HtmlForm headerHtmlForm =
        getHtmlFormFromResource(
            headerFormResource, resourceFactory, formService, htmlFormEntryService);
    model.addAttribute("headerForm", headerForm);

    Encounter headerEncounter = null;
    List<Encounter> headerEncounters = getEncountersForForm(patient, headerHtmlForm);
    if (headerEncounters.size() > 0) {
      headerEncounter = headerEncounters.get(headerEncounters.size() - 1); // Most recent
      if (headerEncounters.size() > 1) {
        alerts.add(
            "WARNING:  More than one "
                + headerHtmlForm.getName()
                + " encounters exist for this patient.  Displaying the most recent only.");
      }
      allEncounters.add(headerEncounter);
    }
    model.addAttribute("headerEncounter", headerEncounter);

    Map<String, HtmlForm> flowsheetForms = new LinkedHashMap<String, HtmlForm>();
    Map<String, List<Integer>> flowsheetEncounters = new LinkedHashMap<String, List<Integer>>();
    if (flowsheets != null) {
      for (String flowsheet : flowsheets) {
        String flowsheetResource = "pihmalawi:htmlforms/" + flowsheet + ".xml";
        HtmlForm htmlForm =
            getHtmlFormFromResource(
                flowsheetResource, resourceFactory, formService, htmlFormEntryService);
        flowsheetForms.put(flowsheet, htmlForm);
        List<Integer> encIds = new ArrayList<Integer>();
        List<Encounter> encounters = getEncountersForForm(patient, htmlForm);
        for (Encounter e : encounters) {
          encIds.add(e.getEncounterId());
          allEncounters.add(e);
        }
        flowsheetEncounters.put(flowsheet, encIds);
      }
    }
    model.addAttribute("flowsheetForms", flowsheetForms);
    model.addAttribute("flowsheetEncounters", flowsheetEncounters);

    model.addAttribute("alerts", alerts);

    if (defaultLocation == null) {
      Date maxDate = null;
      if (allEncounters.size() > 0) {
        for (Encounter e : allEncounters) {
          if (maxDate == null || maxDate.compareTo(e.getEncounterDatetime()) < 0) {
            maxDate = e.getEncounterDatetime();
            defaultLocation = e.getLocation();
          }
        }
      }
    }
    model.addAttribute(
        "defaultLocationId", defaultLocation == null ? null : defaultLocation.getLocationId());
    model.addAttribute("viewOnly", viewOnly == Boolean.TRUE);

    model.addAttribute(
        "returnUrl",
        ui.pageLink(
            "pihmalawi",
            "mastercard",
            SimpleObject.create(
                "patientId",
                patient.getId(),
                "headerForm",
                headerForm,
                "flowsheets",
                flowsheets,
                "viewOnly",
                viewOnly)));
  }
 /** Gets whether report profiling is enabled */
 @AppAction(EmrConstants.APP_DEVELOPER)
 public SimpleObject getReportProfilingEnabled() {
   return SimpleObject.create(
       "enabled", Level.TRACE.equals(LogManager.getLogger(EvaluationProfiler.class).getLevel()));
 }
 /**
  * Executes a groovy script
  *
  * @param script the script
  * @return the result as a simple object {result, output, stacktrace}
  */
 @AppAction(EmrConstants.APP_DEVELOPER)
 public SimpleObject executeGroovy(@RequestParam("script") String script) {
   String[] result = GroovyUtil.getService().evaluate(script);
   return SimpleObject.create("result", result[0], "output", result[1], "stacktrace", result[2]);
 }