Пример #1
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
  @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 static JSONArray getAllGlobalNotesOnASearch(String searchPhrase, Integer patientId) {
    JSONArray jsonArr = new JSONArray();
    List<ChartSearchNote> allNotes = chartSearchService.getAllSearchNotes();
    List<ChartSearchNote> allGlobalNotes = new ArrayList<ChartSearchNote>();

    for (ChartSearchNote note : allNotes) {
      if (note.getPatient().getPatientId().equals(patientId)
          && note.getSearchPhrase().equals(searchPhrase)
          && note.getPriority().equals("HIGH")) {
        allGlobalNotes.add(note);
      }
    }

    if (!allGlobalNotes.isEmpty()) {
      for (ChartSearchNote note : allGlobalNotes) {
        JSONObject json = new JSONObject();
        String userName = note.getNoteOwner().getUsername();
        String systemId = note.getNoteOwner().getSystemId();

        json.put("uuid", note.getUuid());
        json.put("createdOrLastModifiedAt", note.getCreatedOrLastModifiedAt().getTime());
        json.put(
            "formatedCreatedOrLastModifiedAt",
            Context.getDateFormat().format(note.getCreatedOrLastModifiedAt()));
        json.put("backgroundColor", note.getDisplayColor());

        addPhraseAndCommentNotesAttributes(note, json);

        json.put("noteOwner", null == userName ? systemId : userName);

        jsonArr.add(json);
      }
    }
    return jsonArr;
  }
 @InitBinder
 public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
     throws Exception {
   SimpleDateFormat dateFormat = Context.getDateFormat();
   dateFormat.setLenient(false);
   binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true, 10));
   binder.registerCustomEditor(Concept.class, new ConceptEditor());
   binder.registerCustomEditor(Patient.class, new PatientEditor());
   binder.registerCustomEditor(Encounter.class, new EncounterEditor());
 }
  @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
  @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());
    }
  }
  /**
   * Allows for Integers to be used as values in input tags. Normally, only strings and lists are
   * expected
   *
   * @see
   *     org.springframework.web.servlet.mvc.BaseCommandController#initBinder(javax.servlet.http.HttpServletRequest,
   *     org.springframework.web.bind.ServletRequestDataBinder)
   */
  protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder)
      throws Exception {
    super.initBinder(request, binder);

    Locale locale = Context.getLocale();
    NumberFormat nf = NumberFormat.getInstance(locale);

    // NumberFormat nf = NumberFormat.getInstance(new Locale("en_US"));
    binder.registerCustomEditor(
        java.lang.Integer.class, new CustomNumberEditor(java.lang.Integer.class, nf, true));
    binder.registerCustomEditor(
        java.util.Date.class, new CustomDateEditor(Context.getDateFormat(), true, 10));
  }
Пример #9
0
 /**
  * @return the datetime representation of the result <em>value</em> (not to be confused with the
  *     result's own datetime). For non-datetime results, this will return the overridden datetime
  *     value (if specifically defined) or datetime representation of the default datatype. If the
  *     result is a list, then the datetime representation of the first member is returned.
  *     <table>
  *         <th>
  *         <td>Datatype</td>
  *         <td>Returns</td></th>
  *         <tr>
  *         <td>BOOLEAN</td>
  *         <td>null</td>
  *         </tr>
  *         <tr>
  *         <td>CODED</td>
  *         <td>null</td>
  *         </tr>
  *         <tr>
  *         <td>NUMERIC</td>
  *         <td>null</td>
  *         </tr>
  *         <tr>
  *         <td>TEXT</td>
  *         <td>If the text can be parsed into a date, then that value is returned;<br>
  *         otherwise returns <em>null</em></td>
  *         </tr>
  *         </table>
  */
 public Date toDatetime() {
   if (isSingleResult()) {
     if (valueDatetime != null) {
       return valueDatetime;
     }
     if (datatype == Datatype.TEXT && valueText != null) {
       try {
         return Context.getDateFormat().parse(valueText);
       } catch (Exception e) {
       }
     }
     return valueDatetime;
   }
   return this.get(0).toDatetime();
 }
 private static JSONObject generateHistoryJSON(ChartSearchHistory history) {
   JSONObject json;
   json = new JSONObject();
   json.put("searchPhrase", history.getSearchPhrase());
   json.put(
       "lastSearchedAt",
       history
           .getLastSearchedAt()
           .getTime()); // passing timestamp from java to client js is a better practice
   json.put(
       "formattedLastSearchedAt", Context.getDateFormat().format(history.getLastSearchedAt()));
   json.put("uuid", history.getUuid());
   json.put("patientId", history.getPatient().getPatientId());
   json.put("patientFamilyName", history.getPatient().getPersonName().getFamilyName());
   return json;
 }
  /**
   * Searches for Person records that have a name similar to the given name, a birthdate that is
   * null or within a few years of the given birthdate, and a gender that matches. Note: this method
   * contains a non-backwards-compatible change between 1.5 and 1.6, since DWR has trouble with
   * method overloading. The String personType parameter was removed, since User no longer extends
   * Person
   *
   * @param name
   * @param birthdate
   * @param age
   * @param gender
   * @return list of people
   */
  public List<?> getSimilarPeople(String name, String birthdate, String age, String gender) {
    Vector<Object> personList;

    Integer userId = Context.getAuthenticatedUser().getUserId();
    log.info(userId + "|" + name + "|" + birthdate + "|" + age + "|" + gender);

    PersonService ps = Context.getPersonService();

    Integer d = null;
    birthdate = birthdate.trim();
    age = age.trim();
    if (birthdate.length() > 0) {
      // extract the year from the given birthdate string
      DateFormat format = Context.getDateFormat();
      Date dateObject = null;
      try {
        dateObject = format.parse(birthdate);
      } catch (Exception e) {
        log.error("Error during parse birthdate", e);
      }

      if (dateObject != null) {
        Calendar c = Calendar.getInstance();
        c.setTime(dateObject);
        d = c.get(Calendar.YEAR);
      }
    } else if (age.length() > 0) {
      // calculate their birth year from the given age string
      Calendar c = Calendar.getInstance();
      c.setTime(new Date());
      d = c.get(Calendar.YEAR);
      d = d - Integer.parseInt(age);
    }

    if (gender.length() < 1) {
      gender = null;
    }

    Set<Person> persons = ps.getSimilarPeople(name, d, gender);

    personList = new Vector<Object>(persons.size());
    for (Person p : persons) {
      personList.add(PersonListItem.createBestMatch(p));
    }

    return personList;
  }
Пример #12
0
 /**
  * Converts a string to specified type
  *
  * @param val the string to convert
  * @param clazz the type to convert to
  * @return an instance of the specified type, with it's value set to val
  */
 public static Object convertToType(String val, Class<?> clazz) {
   if (val == null) return null;
   if ("".equals(val) && !String.class.equals(clazz)) return null;
   if (Location.class.isAssignableFrom(clazz)) {
     LocationEditor ed = new LocationEditor();
     ed.setAsText(val);
     return ed.getValue();
   } else if (User.class.isAssignableFrom(clazz)) {
     UserEditor ed = new UserEditor();
     ed.setAsText(val);
     return ed.getValue();
   } else if (Date.class.isAssignableFrom(clazz)) {
     try {
       DateFormat df = Context.getDateFormat();
       df.setLenient(false);
       return df.parse(val);
     } catch (ParseException e) {
       throw new IllegalArgumentException(e);
     }
   } else if (Double.class.isAssignableFrom(clazz)) {
     return Double.valueOf(val);
   } else if (Integer.class.isAssignableFrom(clazz)) {
     return Integer.valueOf(val);
   } else if (Concept.class.isAssignableFrom(clazz)) {
     ConceptEditor ed = new ConceptEditor();
     ed.setAsText(val);
     return ed.getValue();
   } else if (Patient.class.isAssignableFrom(clazz)) {
     PatientEditor ed = new PatientEditor();
     ed.setAsText(val);
     return ed.getValue();
   } else if (Person.class.isAssignableFrom(clazz)) {
     PersonEditor ed = new PersonEditor();
     ed.setAsText(val);
     return ed.getValue();
   } else {
     return val;
   }
 }
  @Test
  @Verifies(
      value = "should return encounter with all child objects voided according to schema",
      method = "voidEncounterByHtmlFormSchema")
  public void testVoidEncounterByHtmlFormSchema_shouldReturnEncounterCorrectly() 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
    TestUtil.addObs(e, 3017, Context.getConceptService().getConcept(767), date); // matches
    TestUtil.addObs(e, 3032, new Date(), date); // matches
    TestUtil.addObs(e, 1, 5000, date); //   matches
    TestUtil.addObs(e, 2, 5000, date); // not in form schema
    TestUtil.addObs(e, 3, 5000, date); // not in form schema
    TestUtil.addObs(e, 6, "blah blah", date); //   matches
    // 1004 is ANOTHER ALLERGY CONSTRUCT, 1005 is HYPER-ALLERGY CODED, 1001 is PENICILLIN
    TestUtil.addObsGroup(
        e,
        1004,
        new Date(),
        1005,
        Context.getConceptService().getConcept(1001),
        new Date()); // matches
    // 7 IS ALLERGY CONSTRUCT, 1000 IS ALLERGY CODED, 1003 IS OPENMRS
    TestUtil.addObsGroup(
        e,
        7,
        new Date(),
        1000,
        Context.getConceptService().getConcept(1003),
        new Date()); // matches
    TestUtil.addObsGroup(
        e,
        1000,
        new Date(),
        7,
        Context.getConceptService().getConcept(1003),
        new Date()); // does not match
    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);

    // this is going to test out the voided state of the obs in the encounter after processing:
    Assert.assertTrue(!e.isVoided());
    for (Obs o : e.getAllObs(true)) {
      if (o.getConcept().getConceptId().equals(2474)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(3017)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(3032)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(1)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(2)) Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(3)) Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(6)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(1004)) Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(1005)) Assert.assertTrue(o.isVoided());

      // obsGroups
      if (o.getConcept().getConceptId().equals(7) && o.isObsGrouping())
        Assert.assertTrue(o.isVoided());
      if (o.getConcept().getConceptId().equals(7) && !o.isObsGrouping())
        Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(1000) && o.isObsGrouping())
        Assert.assertTrue(!o.isVoided()); // not matched
      if (o.getConcept().getConceptId().equals(1000) && !o.isObsGrouping())
        Assert.assertTrue(o.isVoided());
    }
  }
  @Override
  public String getOverrideContent(String str) {
    if (!Context.isAuthenticated()) {
      return "";
    }
    String gp =
        Context.getAdministrationService()
            .getGlobalProperty("htmlformflowsheet.patientChartFormIds");

    if (StringUtils.isEmpty(gp)) {
      return "";
    }

    StringBuilder sbExisting = new StringBuilder("");
    StringBuilder sbNonExisting = new StringBuilder("");
    try {
      String patientId = this.getParameterMap().get("patientId");
      Patient p = Context.getPatientService().getPatient(Integer.valueOf(patientId));

      for (StringTokenizer st = new StringTokenizer(gp, ","); st.hasMoreTokens(); ) {

        Map<Integer, Set<Integer>> progForms = new HashMap<Integer, Set<Integer>>();
        Set<Integer> programIds = new HashSet<Integer>();

        String formId = st.nextToken().trim();
        if (formId.contains(":")) {
          String[] formIdSplit = formId.split(":");
          formId = formIdSplit[0];
          // check for required programs:
          String programInfo = formIdSplit[1];
          if (programInfo.contains("|")) {
            for (StringTokenizer strTok = new StringTokenizer(programInfo, "|");
                strTok.hasMoreTokens(); ) {
              String sTmp = strTok.nextToken().trim();
              addFormToProgramList(progForms, Integer.valueOf(formId), Integer.valueOf(sTmp));
              programIds.add(Integer.valueOf(sTmp));
            }
          } else {
            // todo: support lookup programs by uuid and forms by uuid?
            addFormToProgramList(progForms, Integer.valueOf(formId), Integer.valueOf(programInfo));
            programIds.add(Integer.valueOf(programInfo));
          }
        }
        Form form = HtmlFormFlowsheetUtil.getFormFromString(formId);
        List<PatientProgram> pps =
            Context.getProgramWorkflowService()
                .getPatientPrograms(p, null, null, null, null, null, false);
        List<Encounter> encs =
            Context.getEncounterService()
                .getEncounters(
                    p, null, null, null, Collections.singletonList(form), null, null, false);

        //	            for (Map.Entry<Integer, Set<Integer>> m : progForms.entrySet()){
        //	            	System.out.println(m.getKey()+ ":" + m.getValue());
        //	            }

        // 1. no program association to form.  always show.
        if (progForms.get(Integer.valueOf(formId)) == null
            || progForms.get(Integer.valueOf(formId)).size() == 0) {
          if (encs.size() == 0) {
            // if no encs, show add new
            sbNonExisting.append(
                " | <a href=\"/"
                    + WebConstants.WEBAPP_NAME
                    + "/module/htmlformentry/htmlFormEntry.form?personId="
                    + p.getPersonId()
                    + "&patientId="
                    + p.getPatientId()
                    + "&returnUrl=&formId="
                    + form.getFormId()
                    + "\">"
                    + form.getName()
                    + "</a> | ");
          } else {
            // if encs, show existing flowsheet parent(s)
            for (Encounter e : encs) {
              sbExisting.append(
                  " | <a href=\"/"
                      + WebConstants.WEBAPP_NAME
                      + "/module/htmlformentry/htmlFormEntry.form?encounterId="
                      + e.getEncounterId()
                      + "&mode=EDIT\">"
                      + form.getName()
                      + " "
                      + "("
                      + Context.getDateFormat().format(e.getEncounterDatetime())
                      + ")</a> | ");
            }
          }
        } else {
          // 2. program(s) specified for form
          // this builds a map of encounter corresponding to the parent form creation to the
          // patientProgram is was created in.
          Map<Encounter, PatientProgram> encounterToPatientProgram =
              new HashMap<Encounter, PatientProgram>();
          for (Encounter e : encs) {
            for (PatientProgram pp : pps) {

              // if encounter is later than start date and less than end date or end date is null
              if (programIds.contains(pp.getProgram().getProgramId())
                  && e.getEncounterDatetime().getTime() >= pp.getDateEnrolled().getTime()
                  && ((pp.getDateCompleted() == null
                      || pp.getDateCompleted().getTime() >= e.getEncounterDatetime().getTime()))) {
                // encounter is in patientprogram
                encounterToPatientProgram.put(e, pp);
              }
            }
          }
          // show existing based on the map
          for (Map.Entry<Encounter, PatientProgram> m : encounterToPatientProgram.entrySet()) {
            sbExisting.append(
                " | <a href=\"/"
                    + WebConstants.WEBAPP_NAME
                    + "/module/htmlformentry/htmlFormEntry.form?encounterId="
                    + m.getKey().getEncounterId()
                    + "&mode=EDIT\">"
                    + form.getName());
            if (m.getValue() != null) {
              sbExisting.append(
                  " "
                      + "("
                      + Context.getDateFormat().format(m.getValue().getDateEnrolled())
                      + " - ");
              if (m.getValue().getDateCompleted() != null)
                sbExisting.append(Context.getDateFormat().format(m.getValue().getDateCompleted()));
              sbExisting.append(")");
            }
            sbExisting.append("</a> | ");
          }

          // show add new
          // if patient is in program currently, AND patient doesn't have an encounter for this
          // program
          PatientProgram ppActive = activePatientProgram(pps, programIds);
          boolean found = false;
          if (ppActive != null) {
            for (Map.Entry<Encounter, PatientProgram> m : encounterToPatientProgram.entrySet()) {
              if (m.getValue() != null && m.getValue().equals(ppActive)) found = true;
            }
            if (!found)
              sbNonExisting.append(
                  " | <a href=\"/"
                      + WebConstants.WEBAPP_NAME
                      + "/module/htmlformentry/htmlFormEntry.form?personId="
                      + p.getPersonId()
                      + "&patientId="
                      + p.getPatientId()
                      + "&returnUrl=&formId="
                      + form.getFormId()
                      + "\"> "
                      + form.getName()
                      + "</a> | ");
          }
        }
      }
      String retString = "<table><tr><td>";
      if (!sbExisting.toString().equals(""))
        retString += "Existing Patient Chart(s): " + sbExisting.toString();
      retString += "</td></tr><tr><td>";
      if (!sbNonExisting.toString().equals(""))
        retString += "Create A New Patient Charts: " + sbNonExisting.toString();
      retString += "</td></tr></table>";
      return retString.replace("|  |", " | ");

    } catch (Exception ex) {
      ex.printStackTrace();
      return "";
    }
  }