/** @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);
  }
  @Override
  protected void addColumns(CohortReportDescriptor report, PatientDataSetDefinition dsd) {
    PatientIdentifierType upn =
        MetadataUtils.existing(
            PatientIdentifierType.class, HivMetadata._PatientIdentifierType.UNIQUE_PATIENT_NUMBER);
    DataDefinition identifierDefUpn =
        new ConvertedPatientDataDefinition(
            "identifier",
            new PatientIdentifierDataDefinition(upn.getName(), upn),
            new IdentifierConverter());

    PatientIdentifierType districtNo =
        MetadataUtils.existing(
            PatientIdentifierType.class, TbMetadata._PatientIdentifierType.DISTRICT_REG_NUMBER);
    DataDefinition identifierDefDn =
        new ConvertedPatientDataDefinition(
            "identifier",
            new PatientIdentifierDataDefinition(upn.getName(), districtNo),
            new IdentifierConverter());

    addStandardColumns(report, dsd);
    dsd.addColumn("Unique Patient Number", identifierDefUpn, "");
    dsd.addColumn("District Registration Number", identifierDefDn, "");
    dsd.addColumn(
        "Due date",
        new CalculationDataDefinition("Date Eligible", new NeedsTbSputumTestDateCalculation()),
        "",
        new CalculationResultConverter());
  }
  private void verifySentinelData() {
    // Verify a few pieces of sentinel data that should have been in the packages
    assertNotNull(userService.getRole("Organizational: Doctor"));
    MetadataUtils.existing(Role.class, RolePrivilegeMetadata._Role.ORGANIZATIONAL_DOCTOR);
    MetadataUtils.existing(
        Privilege.class, RolePrivilegeMetadata._Privilege.APP_COREAPPS_FIND_PATIENT);

    assertThat(
        conceptService.getConcept(5085).getUuid(), is("5085AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));
    assertThat(
        conceptService.getConcept(159947).getUuid(), is("159947AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"));

    assertThat(conceptService.getAllConcepts().size(), is(435));
  }
  /**
   * @see
   *     org.openmrs.module.htmlformentry.element.HtmlGeneratorElement#generateHtml(org.openmrs.module.htmlformentry.FormEntryContext)
   */
  @Override
  public String generateHtml(FormEntryContext context) {
    if (context.getExistingPatient() == null) {
      return "";
    }

    KenyaUiUtils kenyaui = Context.getRegisteredComponents(KenyaUiUtils.class).get(0);

    PatientWrapper patient = new PatientWrapper(context.getExistingPatient());

    Obs obs = patient.lastObs(MetadataUtils.getConcept(conceptId));

    StringBuilder sb = new StringBuilder("<span>");

    if (obs != null) {
      sb.append(kenyaui.formatObsValue(obs));

      if (showDate) {
        sb.append(" <small>(" + kenyaui.formatDate(obs.getObsDatetime()) + ")</small>");
      }
    } else if (noneMessage != null) {
      sb.append(noneMessage);
    }

    sb.append("</span>");
    return sb.toString();
  }
  /** @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);
  }
  /** Setup each test */
  @Before
  public void setup() throws Exception {
    commonMetadata.install();

    VisitType outpatient = MetadataUtils.getVisitType(CommonMetadata._VisitType.OUTPATIENT);

    // Patient #7 has two visits on 1-Jan-2012 (from 9am to 10am and another from 11am to 12pm)
    TestUtils.saveVisit(
        TestUtils.getPatient(7),
        outpatient,
        TestUtils.date(2012, 1, 1, 9, 0, 0),
        TestUtils.date(2012, 1, 1, 10, 0, 0));
    TestUtils.saveVisit(
        TestUtils.getPatient(7),
        outpatient,
        TestUtils.date(2012, 1, 1, 11, 0, 0),
        TestUtils.date(2012, 1, 1, 12, 0, 0));

    // Patient #8 has visit on 2-Jan-2012
    TestUtils.saveVisit(
        TestUtils.getPatient(8),
        outpatient,
        TestUtils.date(2012, 1, 2, 9, 0, 0),
        TestUtils.date(2012, 1, 2, 10, 0, 0));
  }
 /**
  * Patients who completed program ${onOrAfter} and ${onOrBefore}
  *
  * @return the cohort definition
  */
 public CohortDefinition compltedProgram() {
   ProgramEnrollmentCohortDefinition cd = new ProgramEnrollmentCohortDefinition();
   cd.setName("Those patients who completed program on date");
   cd.addParameter(new Parameter("completedOnOrBefore", "Complete Date", Date.class));
   cd.setPrograms(Arrays.asList(MetadataUtils.existing(Program.class, HivMetadata._Program.HIV)));
   return cd;
 }
  /**
   * @see org.openmrs.calculation.patient.PatientCalculation#evaluate(java.util.Collection,
   *     java.util.Map, org.openmrs.calculation.patient.PatientCalculationContext)
   */
  @Override
  public CalculationResultMap evaluate(
      Collection<Integer> cohort,
      Map<String, Object> parameterValues,
      PatientCalculationContext context) {

    Program mchcsProgram = MetadataUtils.getProgram(MchMetadata._Program.MCHCS);

    // Get all patients who are alive and in MCH-CS program
    Set<Integer> alive = Filters.alive(cohort, context);
    Set<Integer> inMchcsProgram = Filters.inProgram(mchcsProgram, alive, context);

    // get wheather the child is HIV Exposed
    CalculationResultMap lastChildHivStatus =
        Calculations.lastObs(
            Dictionary.getConcept(Dictionary.CHILDS_CURRENT_HIV_STATUS), inMchcsProgram, context);
    CalculationResultMap medOrdersObss =
        Calculations.allObs(Dictionary.getConcept(Dictionary.MEDICATION_ORDERS), cohort, context);

    // Get concepts for  medication prophylaxis
    Concept nvp = Dictionary.getConcept(Dictionary.NEVIRAPINE);
    Concept nvpazt3tc = Dictionary.getConcept(Dictionary.LAMIVUDINE_NEVIRAPINE_ZIDOVUDINE);
    Concept hivExposed = Dictionary.getConcept(Dictionary.EXPOSURE_TO_HIV);

    CalculationResultMap ret = new CalculationResultMap();

    for (Integer ptId : cohort) {
      boolean notOnPcp = false;

      // checking wheather the infant is in mchcs program, alive and HEI
      Obs hivStatusObs = EmrCalculationUtils.obsResultForPatient(lastChildHivStatus, ptId);
      if (inMchcsProgram.contains(ptId)
          && lastChildHivStatus != null
          && hivStatusObs != null
          && (hivStatusObs.getValueCoded().equals(hivExposed))) {
        notOnPcp = true;
        ListResult patientMedOrders = (ListResult) medOrdersObss.get(ptId);
        if (patientMedOrders != null) {
          // Look through list of medication order obs for any  CTX
          List<Obs> medOrderObsList = CalculationUtils.extractResultValues(patientMedOrders);
          for (Obs medOrderObs : medOrderObsList) {
            if (medOrderObs.getValueCoded().equals(nvp)
                || medOrderObs.getValueCoded().equals(nvpazt3tc)) {
              notOnPcp = false;
              break;
            }
          }
        }
      }
      ret.put(ptId, new BooleanResult(notOnPcp, this, context));
    }

    return ret;
  }
  /**
   * Evaluates the calculation
   *
   * @should calculate false for deceased patients
   * @should calculate false for patients not in HIV program
   * @should calculate false for patients with an encounter in last LOST_TO_FOLLOW_UP_THRESHOLD_DAYS
   *     days days since appointment date
   * @should calculate true for patient with no encounter in last LOST_TO_FOLLOW_UP_THRESHOLD_DAYS
   *     days days since appointment date
   */
  @Override
  public CalculationResultMap evaluate(
      Collection<Integer> cohort, Map<String, Object> arg1, PatientCalculationContext context) {

    Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);
    Concept reasonForDiscontinuation =
        Dictionary.getConcept(Dictionary.REASON_FOR_PROGRAM_DISCONTINUATION);
    Concept transferout = Dictionary.getConcept(Dictionary.TRANSFERRED_OUT);

    Set<Integer> alive = Filters.alive(cohort, context);
    Set<Integer> inHivProgram = Filters.inProgram(hivProgram, alive, context);

    // CalculationResultMap lastEncounters = Calculations.lastEncounter(null, inHivProgram,
    // context);
    CalculationResultMap lastReturnDateObss =
        Calculations.lastObs(
            Dictionary.getConcept(Dictionary.RETURN_VISIT_DATE), inHivProgram, context);
    CalculationResultMap lastProgramDiscontinuation =
        Calculations.lastObs(reasonForDiscontinuation, cohort, context);

    CalculationResultMap ret = new CalculationResultMap();
    for (Integer ptId : cohort) {
      boolean lost = false;

      // Is patient alive and in the HIV program
      if (alive.contains(ptId)) {

        // Patient is lost if no encounters in last X days
        // Encounter lastEncounter = EmrCalculationUtils.encounterResultForPatient(lastEncounters,
        // ptId);
        Date lastScheduledReturnDate =
            EmrCalculationUtils.datetimeObsResultForPatient(lastReturnDateObss, ptId);
        Obs discontuation =
            EmrCalculationUtils.obsResultForPatient(lastProgramDiscontinuation, ptId);
        if (lastScheduledReturnDate != null) {
          if (daysSince(lastScheduledReturnDate, context)
              > HivConstants.LOST_TO_FOLLOW_UP_THRESHOLD_DAYS) {
            lost = true;
          }
          if (discontuation != null && discontuation.getValueCoded().equals(transferout)) {
            lost = false;
          }
        }
      }
      ret.put(ptId, new SimpleResult(lost, this, context));
    }
    return ret;
  }
  @Test
  public void setPreferredConceptName_shouldTagShortName() throws Exception {
    metadataDeployService.installBundles(Arrays.<MetadataBundle>asList(ebolaMetadata));
    ConceptNameTag nameTag =
        MetadataUtils.existing(ConceptNameTag.class, EbolaMetadata._ConceptNameTag.PREFERRED);

    String uuid = "c607c80f-1ea9-4da3-bb88-6276ce8868dd";
    assertThat(
        conceptService.getConceptByUuid(uuid).getPreferredName(Locale.ENGLISH).getName(),
        is("WEIGHT (KG)"));

    new EbolaExampleActivator().setPreferredConceptName(conceptService, uuid, "WT");
    assertThat(
        conceptService.getConceptByUuid(uuid).getPreferredName(Locale.ENGLISH).getName(),
        is("WEIGHT (KG)"));
    assertThat(
        conceptService.getConceptByUuid(uuid).findNameTaggedWith(nameTag).getName(), is("WT"));
  }
  /**
   * Sets a attribute value of this person. If the value is blank then any existing attribute will
   * be voided.
   *
   * @param attrTypeUuid the attribute type UUID
   * @param value the value
   */
  protected void setAsAttribute(String attrTypeUuid, String value) {
    PersonAttribute attr = findFirstAttribute(attrTypeUuid);

    if (StringUtils.isNotBlank(value)) {
      if (attr == null) {
        attr = new PersonAttribute();
        attr.setAttributeType(MetadataUtils.existing(PersonAttributeType.class, attrTypeUuid));
        attr.setValue(value);
        target.addAttribute(attr);
      } else {
        attr.setValue(value);
      }
    } else if (attr != null) {
      attr.setVoided(true);
      attr.setDateVoided(new Date());
      attr.setVoidedBy(Context.getAuthenticatedUser());
    }
  }
 /**
  * @see org.openmrs.calculation.patient.PatientCalculation#evaluate(java.util.Collection,
  *     java.util.Map, org.openmrs.calculation.patient.PatientCalculationContext)
  * @param cohort
  * @param parameterValues
  * @param context
  * @return true for deceased patients
  * @return False for non deceased patients
  */
 @Override
 public CalculationResultMap evaluate(
     Collection<Integer> cohort,
     Map<String, Object> parameterValues,
     PatientCalculationContext context) {
   Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);
   Set<Integer> inHivProgram = Filters.inProgram(hivProgram, cohort, context);
   Set<Integer> alive = Filters.alive(cohort, context);
   CalculationResultMap ret = new CalculationResultMap();
   for (Integer ptId : cohort) {
     boolean dead = false;
     if (inHivProgram.contains(ptId) && !(alive.contains(ptId))) {
       dead = true;
     }
     ret.put(ptId, new SimpleResult(dead, this, context));
   }
   return ret;
 }
  @Override
  protected void addColumns(CohortReportDescriptor report, PatientDataSetDefinition dsd) {
    PatientIdentifierType upn =
        MetadataUtils.existing(
            PatientIdentifierType.class, HivMetadata._PatientIdentifierType.UNIQUE_PATIENT_NUMBER);
    DataDefinition identifierDef =
        new ConvertedPatientDataDefinition(
            "identifier",
            new PatientIdentifierDataDefinition(upn.getName(), upn),
            new IdentifierConverter());

    addStandardColumns(report, dsd);
    dsd.addColumn("UPN", identifierDef, "");
    dsd.addColumn(
        "Death date",
        new CalculationDataDefinition("Death date", new DateOfDeathCalculation()),
        "",
        new CalculationResultConverter());
  }
  /**
   * @see
   *     org.openmrs.module.kenyacore.report.builder.AbstractCohortReportBuilder#addColumns(CohortReportDescriptor,
   *     PatientDataSetDefinition)
   */
  @Override
  protected void addColumns(HybridReportDescriptor report, PatientDataSetDefinition dsd) {

    PatientIdentifierType upn =
        MetadataUtils.existing(
            PatientIdentifierType.class, HivMetadata._PatientIdentifierType.UNIQUE_PATIENT_NUMBER);
    DataDefinition identifierDef =
        new ConvertedPatientDataDefinition(
            "identifier",
            new PatientIdentifierDataDefinition(upn.getName(), upn),
            new IdentifierConverter());
    DataConverter nameFormatter = new ObjectFormatter("{familyName}, {givenName}");
    DataDefinition nameDef =
        new ConvertedPersonDataDefinition("name", new PreferredNameDataDefinition(), nameFormatter);

    dsd.setName("artCohortAnalysis");
    dsd.addColumn("id", new PatientIdDataDefinition(), "");
    dsd.addColumn("Name", nameDef, "");
    dsd.addColumn("UPN", identifierDef, "");
    dsd.addColumn(
        "Enrollment into care date",
        hivProgramEnrollment(),
        "onDate=${endDate}",
        new CalculationResultConverter());
    dsd.addColumn("DOB", new BirthdateDataDefinition(), "", new BirthdateConverter());
    dsd.addColumn(
        "DOB approx",
        new CalculationDataDefinition("DOB approx", new IsBirthDateApproximatedCalculation()),
        "",
        new CalculationResultConverter());
    dsd.addColumn(
        "Age at ART initiation",
        new CalculationDataDefinition("Age at ART initiation", new AgeAtARTInitiationCalculation()),
        "",
        new CalculationResultConverter());
    dsd.addColumn("Sex", new GenderDataDefinition(), "");
    dsd.addColumn("TI", ti(), "", new TransferInAndDateConverter("state"));
    dsd.addColumn("Date TI", ti(), "", new TransferInAndDateConverter("date"));
    dsd.addColumn("TO", to(report), "onDate=${endDate}", new TransferInAndDateConverter("state"));
    dsd.addColumn(
        "Date TO", to(report), "onDate=${endDate}", new TransferInAndDateConverter("date"));
    dsd.addColumn(
        "ARV Start Date",
        new CalculationDataDefinition("ARV Start Date", new DateARV1Calculation()),
        "",
        new CalculationResultConverter());
    dsd.addColumn(
        "Days from enrollment in care to ART Initiation",
        new CalculationDataDefinition(
            "Days from enrollment in care to ART Initiation",
            new DaysFromEnrollmentToArtInitiationCalculation()),
        "",
        new CalculationResultConverter());
    dsd.addColumn(
        "Days from ART eligibility to ART Initiation",
        fromEligibilityToArtStart(report),
        "onDate=${endDate}",
        new CalculationResultConverter());
    dsd.addColumn(
        "Date first medically eligible for ART",
        dateAndReasonFirstMedicallyEligibleForArtCalculation(report),
        "onDate=${endDate}",
        new MedicallyEligibleConverter("date"));
    dsd.addColumn(
        "Reason first medically eligible For ART",
        dateAndReasonFirstMedicallyEligibleForArtCalculation(report),
        "onDate=${endDate}",
        new MedicallyEligibleConverter("reason"));
    dsd.addColumn(
        "ART baseline CD4 count",
        baselineCd4(report),
        "onDate=${endDate}",
        new Cd4ValueAndDateConverter("value"));
    dsd.addColumn(
        "Date of ART baseline CD4 count",
        baselineCd4(report),
        "onDate=${endDate}",
        new Cd4ValueAndDateConverter("date"));
    dsd.addColumn(
        "Initial ART regimen",
        new CalculationDataDefinition("First ART regimen", new InitialArtRegimenCalculation()),
        "",
        new RegimenConverter());
    dsd.addColumn(
        "Current ART regimen",
        currentARTRegimen(report),
        "onDate=${endDate}",
        new ArtCohortRegimenConverter());
    dsd.addColumn(
        "Current ART line",
        currentARTRegimen(report),
        "onDate=${endDate}",
        new RegimenLineConverter());
    dsd.addColumn(
        "CD4 at end of follow up",
        currentCd4Count(report),
        "onDate=${endDate}",
        new CurrentCd4Converter("value"));
    dsd.addColumn(
        "CD4 at end of follow up date",
        currentCd4Count(report),
        "onDate=${endDate}",
        new CurrentCd4Converter("date"));
    dsd.addColumn(
        "Change in cd4 count",
        changeInCd4Count(report),
        "onDate=${endDate}",
        new ChangeInCd4Converter());
    dsd.addColumn(
        "Viral load at end of follow up",
        viralLoad(report),
        "onDate=${endDate}",
        new CurrentCd4Converter("value"));
    dsd.addColumn(
        "Date viral load at end of follow up",
        viralLoad(report),
        "onDate=${endDate}",
        new CurrentCd4Converter("date"));
    dsd.addColumn(
        "Viral suppression",
        viralSuppression(report),
        "onDate=${endDate}",
        new CalculationResultConverter());
    dsd.addColumn(
        "Date of Last visit",
        lastSeen(report),
        "onDate=${endDate}",
        new CalculationResultConverter());
    dsd.addColumn(
        "Date of expected next visit",
        nextAppointmentDate(report),
        "onDate=${endDate}",
        new CalculationResultConverter());
    dsd.addColumn(
        "Date of death", death(report), "onDate=${endDate}", new CalculationResultConverter());
    dsd.addColumn(
        "ART Outcomes",
        patientOutComes(report),
        "onDate=${endDate}",
        new CalculationResultConverter());
  }
  @Override
  public CalculationResultMap evaluate(
      Collection<Integer> cohort,
      Map<String, Object> parameterValues,
      PatientCalculationContext context) {
    Program hivProgram = MetadataUtils.existing(Program.class, HivMetadata._Program.HIV);

    Set<Integer> alive = Filters.alive(cohort, context);
    Set<Integer> inHivProgram = Filters.inProgram(hivProgram, alive, context);

    Set<Integer> aliveAndFemale = Filters.female(Filters.alive(cohort, context), context);

    CalculationResultMap ret = new CalculationResultMap();

    // need to exclude those on ART already
    Set<Integer> onArt =
        CalculationUtils.patientsThatPass(calculate(new OnArtCalculation(), cohort, context));
    // find the observation for viral load recorded
    CalculationResultMap viralLoad =
        Calculations.lastObs(Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD), cohort, context);
    // get a list of all the viral load
    CalculationResultMap viralLoadList =
        Calculations.allObs(Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD), cohort, context);
    // check for non detectables
    CalculationResultMap ldlViralLoad =
        Calculations.allObs(
            Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD_QUALITATIVE), cohort, context);

    // check for test orders
    CalculationResultMap testOrders =
        Calculations.allObs(Dictionary.getConcept(Dictionary.TESTS_ORDERED), cohort, context);

    // check for last ldl
    CalculationResultMap ldlLast =
        Calculations.lastObs(
            Dictionary.getConcept(Dictionary.HIV_VIRAL_LOAD_QUALITATIVE), cohort, context);

    // find for prgnant females

    CalculationResultMap pregStatusObss =
        Calculations.lastObs(
            Dictionary.getConcept(Dictionary.PREGNANCY_STATUS), aliveAndFemale, context);

    // get the initial art start date
    CalculationResultMap artStartDate =
        calculate(new InitialArtStartDateCalculation(), cohort, context);

    for (Integer ptId : cohort) {
      boolean needsViralLoadTest = false;
      Obs viralLoadObs = EmrCalculationUtils.obsResultForPatient(viralLoad, ptId);
      Date dateInitiated = EmrCalculationUtils.datetimeResultForPatient(artStartDate, ptId);
      ListResult listResult = (ListResult) viralLoadList.get(ptId);
      ListResult testOrdersList = (ListResult) testOrders.get(ptId);
      List<Obs> testObsList = CalculationUtils.extractResultValues(testOrdersList);
      List<Obs> listObsViralLoads = CalculationUtils.extractResultValues(listResult);
      ListResult ldlList = (ListResult) ldlViralLoad.get(ptId);
      List<List> listLdl = CalculationUtils.extractResultValues(ldlList);
      Obs lastLdlObs = EmrCalculationUtils.obsResultForPatient(ldlLast, ptId);
      // find pregnancy obs
      Obs pregnantEdd = EmrCalculationUtils.obsResultForPatient(pregStatusObss, ptId);

      // Find latest viral load test order
      Obs lastVlTestOrder = getLatestVlOrder(testObsList);

      if (inHivProgram.contains(ptId) && onArt.contains(ptId)) {
        if (listObsViralLoads.size() == 0
            && listLdl.size() == 0
            && dateInitiated != null
            && (daysSince(dateInitiated, context) >= 180)) {
          needsViralLoadTest = true;
        }
        // need to check here if patient has had any viral load
        /*if(dateInitiated != null && (daysSince(dateInitiated, context) >= 360)) {
            needsViralLoadTest = true;
        }*/

        // those continuing should receive one VL every year
        // pick the date of the last viral load numeric values
        if (viralLoadObs != null && (daysSince(viralLoadObs.getObsDatetime(), context) >= 360)) {
          needsViralLoadTest = true;
        }
        // pick the date of the ldl
        if (lastLdlObs != null && (daysSince(lastLdlObs.getObsDatetime(), context) >= 360)) {
          needsViralLoadTest = true;
        }

        // if vl more than
        if (viralLoadObs != null
            && viralLoadObs.getValueNumeric() > 1000
            && (daysSince(viralLoadObs.getObsDatetime(), context) > 90)) {
          needsViralLoadTest = true;

          if (lastLdlObs != null && (daysSince(lastLdlObs.getObsDatetime(), context) < 360)) {
            needsViralLoadTest = false;
          }
        }

        // check for pregnancy
        if (pregnantEdd != null
            && pregnantEdd.getValueCoded().equals(Dictionary.getConcept(Dictionary.YES))
            && dateInitiated != null) {
          Date whenVLWillBeDue =
              DateUtil.adjustDate(
                  DateUtil.adjustDate(dateInitiated, 6, DurationUnit.MONTHS),
                  -1,
                  DurationUnit.DAYS);
          // if last vl is 6 months older then the patient is due for vl
          if (viralLoadObs == null && lastLdlObs == null) {
            needsViralLoadTest = true;
          }
          if (viralLoadObs == null
              && lastLdlObs == null
              && (context.getNow().after(whenVLWillBeDue))) {
            needsViralLoadTest = true;
          }
          if (viralLoadObs != null
              && viralLoadObs.getValueNumeric() > 1000
              && (monthsBetween(viralLoadObs.getObsDatetime(), context.getNow()) >= 3)) {
            needsViralLoadTest = true;
            if (lastLdlObs != null && (daysSince(lastLdlObs.getObsDatetime(), context) < 360)) {
              needsViralLoadTest = false;
            }
          }
          if (viralLoadObs != null && daysSince(viralLoadObs.getObsDatetime(), context) >= 180) {
            needsViralLoadTest = true;
          }
          if (lastLdlObs != null && daysSince(lastLdlObs.getObsDatetime(), context) >= 180) {
            needsViralLoadTest = true;
          }
        }

        // check if has vl test order within 6 months
        if (lastVlTestOrder != null
            && daysSince(lastVlTestOrder.getObsDatetime(), context) >= 180) {
          needsViralLoadTest = true;
        }

        if (lastVlTestOrder != null && daysSince(lastVlTestOrder.getObsDatetime(), context) < 180) {
          needsViralLoadTest = false;
        }
      }

      ret.put(ptId, new BooleanResult(needsViralLoadTest, this));
    }
    return ret;
  }