use of org.openmrs.module.pihcore.reporting.cohort.definition.ActiveVisitsWithEncountersCohortDefinition in project openmrs-module-pihcore by PIH.
the class ActiveVisitsWithEncountersCohortDefinitionEvaluator method evaluate.
@Override
public EvaluatedCohort evaluate(CohortDefinition cohortDefinition, EvaluationContext context) throws EvaluationException {
ActiveVisitsWithEncountersCohortDefinition cd = (ActiveVisitsWithEncountersCohortDefinition) cohortDefinition;
HqlQueryBuilder encQuery = new HqlQueryBuilder();
encQuery.select("e.patient.id, e.encounterId");
encQuery.from(Encounter.class, "e");
encQuery.whereEqual("e.voided", false);
encQuery.whereEqual("e.visit.voided", false);
encQuery.wherePatientIn("e.patient.id", context);
if (cd.isActive() != null) {
encQuery.whereNull("e.visit.stopDatetime");
}
if (cd.getWhichEncounter() == TimeQualifier.LAST) {
// Ascending since we take last value found
encQuery.orderAsc("e.encounterDatetime").orderAsc("e.dateCreated");
} else if (cd.getWhichEncounter() == TimeQualifier.FIRST) {
// Descending since we take last value found
encQuery.orderDesc("e.encounterDatetime").orderDesc("e.dateCreated");
}
Set<Integer> encountersToInclude = new HashSet<Integer>();
if (cd.getWhichEncounter() == TimeQualifier.LAST || cd.getWhichEncounter() == TimeQualifier.FIRST) {
Map<Integer, Integer> encountersByPatient = evaluationService.evaluateToMap(encQuery, Integer.class, Integer.class, context);
encountersToInclude.addAll(encountersByPatient.values());
} else {
List<Object[]> rawResults = evaluationService.evaluateToList(encQuery, context);
for (Object[] resultRow : rawResults) {
encountersToInclude.add((Integer) resultRow[1]);
}
}
HqlQueryBuilder q = new HqlQueryBuilder();
q.select("e.patient.id");
q.from(Encounter.class, "e");
q.whereIn("e.location", cd.getLocationList());
q.whereIdIn("e.encounterId", encountersToInclude);
Cohort c = new Cohort(evaluationService.evaluateToList(q, Integer.class, context));
return new EvaluatedCohort(c, cohortDefinition, context);
}
Aggregations