use of de.symeda.sormas.api.caze.CaseCriteria in project SORMAS-Project by hzi-braunschweig.
the class PersonFacadeEjb method onPersonChanged.
public void onPersonChanged(PersonDto existingPerson, Person newPerson, boolean syncShares) {
List<Case> personCases = null;
// Do not bother to update existing cases/contacts/eventparticipants on new Persons, as none should exist yet
if (existingPerson != null) {
personCases = caseService.findBy(new CaseCriteria().person(new PersonReferenceDto(newPerson.getUuid())), true);
// Attention: this may lead to infinite recursion when not properly implemented
for (Case personCase : personCases) {
CaseDataDto existingCase = caseFacade.toDto(personCase);
caseFacade.onCaseChanged(existingCase, personCase, syncShares);
}
List<Contact> personContacts = contactService.findBy(new ContactCriteria().setPerson(new PersonReferenceDto(newPerson.getUuid())), null);
// Attention: this may lead to infinite recursion when not properly implemented
for (Contact personContact : personContacts) {
contactFacade.onContactChanged(contactFacade.toDto(personContact), syncShares);
}
List<EventParticipant> personEventParticipants = eventParticipantService.findBy(new EventParticipantCriteria().withPerson(new PersonReferenceDto(newPerson.getUuid())), null);
// Attention: this may lead to infinite recursion when not properly implemented
for (EventParticipant personEventParticipant : personEventParticipants) {
eventParticipantFacade.onEventParticipantChanged(eventFacade.toDto(personEventParticipant.getEvent()), eventParticipantFacade.toDto(personEventParticipant), personEventParticipant, syncShares);
}
// get the updated personCases
personCases = caseService.findBy(new CaseCriteria().person(new PersonReferenceDto(newPerson.getUuid())), true);
// sort cases based on recency
Collections.sort(personCases, (c1, c2) -> CaseLogic.getStartDate(c1.getSymptoms().getOnsetDate(), c1.getReportDate()).before(CaseLogic.getStartDate(c2.getSymptoms().getOnsetDate(), c2.getReportDate())) ? 1 : -1);
if (newPerson.getPresentCondition() != null && existingPerson.getPresentCondition() != newPerson.getPresentCondition()) {
// get the latest case with disease==causeofdeathdisease
Case personCase = personCases.stream().filter(caze -> caze.getDisease() == newPerson.getCauseOfDeathDisease()).findFirst().orElse(null);
if (newPerson.getPresentCondition().isDeceased() && newPerson.getDeathDate() != null && newPerson.getCauseOfDeath() == CauseOfDeath.EPIDEMIC_DISEASE && newPerson.getCauseOfDeathDisease() != null) {
// update the latest associated case
if (personCase != null && personCase.getOutcome() != CaseOutcome.DECEASED && (personCase.getReportDate().before(DateHelper.addDays(newPerson.getDeathDate(), 30)) && personCase.getReportDate().after(DateHelper.subtractDays(newPerson.getDeathDate(), 30)))) {
CaseDataDto existingCase = caseFacade.toDto(personCase);
personCase.setOutcome(CaseOutcome.DECEASED);
personCase.setOutcomeDate(newPerson.getDeathDate());
caseFacade.onCaseChanged(existingCase, personCase, syncShares);
}
} else if (!newPerson.getPresentCondition().isDeceased() && (existingPerson.getPresentCondition() == PresentCondition.DEAD || existingPerson.getPresentCondition() == PresentCondition.BURIED)) {
// Person was put "back alive"
// make sure other values are set to null
newPerson.setCauseOfDeath(null);
newPerson.setCauseOfDeathDisease(null);
newPerson.setDeathPlaceDescription(null);
newPerson.setDeathPlaceType(null);
newPerson.setBurialDate(null);
newPerson.setCauseOfDeathDisease(null);
// update the latest associated case, if it was set to deceased && and if the case-disease was also the causeofdeath-disease
if (personCase != null && personCase.getOutcome() == CaseOutcome.DECEASED) {
CaseDataDto existingCase = caseFacade.toDto(personCase);
personCase.setOutcome(CaseOutcome.NO_OUTCOME);
personCase.setOutcomeDate(null);
caseFacade.onCaseChanged(existingCase, personCase, syncShares);
}
}
} else if (newPerson.getPresentCondition() != null && newPerson.getPresentCondition().isDeceased() && !Objects.equals(newPerson.getDeathDate(), existingPerson.getDeathDate()) && newPerson.getDeathDate() != null) {
// only Deathdate has changed
// update the latest associated case to the new deathdate, if causeOfDeath matches
Case personCase = personCases.isEmpty() ? null : personCases.get(0);
if (personCase != null && personCase.getOutcome() == CaseOutcome.DECEASED && newPerson.getCauseOfDeath() == CauseOfDeath.EPIDEMIC_DISEASE) {
CaseDataDto existingCase = caseFacade.toDto(personCase);
personCase.setOutcomeDate(newPerson.getDeathDate());
caseFacade.onCaseChanged(existingCase, personCase, syncShares);
}
}
}
// Set approximate age if it hasn't been set before
if (newPerson.getApproximateAge() == null && newPerson.getBirthdateYYYY() != null) {
Pair<Integer, ApproximateAgeType> pair = ApproximateAgeHelper.getApproximateAge(newPerson.getBirthdateYYYY(), newPerson.getBirthdateMM(), newPerson.getBirthdateDD(), newPerson.getDeathDate());
newPerson.setApproximateAge(pair.getElement0());
newPerson.setApproximateAgeType(pair.getElement1());
newPerson.setApproximateAgeReferenceDate(newPerson.getDeathDate() != null ? newPerson.getDeathDate() : new Date());
}
// Update caseAge of all associated cases when approximateAge has changed
if (existingPerson != null && existingPerson.getApproximateAge() != newPerson.getApproximateAge()) {
// Update case list after previous onCaseChanged
personCases = caseService.findBy(new CaseCriteria().person(new PersonReferenceDto(newPerson.getUuid())), true);
for (Case personCase : personCases) {
CaseDataDto existingCase = caseFacade.toDto(personCase);
if (newPerson.getApproximateAge() == null) {
personCase.setCaseAge(null);
} else if (newPerson.getApproximateAgeType() == ApproximateAgeType.MONTHS) {
personCase.setCaseAge(0);
} else {
Date now = new Date();
personCase.setCaseAge(newPerson.getApproximateAge() - DateHelper.getYearsBetween(personCase.getReportDate(), now));
if (personCase.getCaseAge() < 0) {
personCase.setCaseAge(0);
}
}
caseFacade.onCaseChanged(existingCase, personCase, syncShares);
}
}
// For newly created persons, assume no registration in external journals
if (existingPerson == null && newPerson.getSymptomJournalStatus() == null) {
newPerson.setSymptomJournalStatus(SymptomJournalStatus.UNREGISTERED);
}
cleanUp(newPerson);
}
use of de.symeda.sormas.api.caze.CaseCriteria in project SORMAS-Project by hzi-braunschweig.
the class CaseFacadeEjb method getExportList.
@Override
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)
public List<CaseExportDto> getExportList(CaseCriteria caseCriteria, Collection<String> selectedRows, CaseExportType exportType, int first, int max, ExportConfigurationDto exportConfiguration, Language userLanguage) {
Boolean previousCaseManagementDataCriteria = caseCriteria.getMustHaveCaseManagementData();
if (CaseExportType.CASE_MANAGEMENT == exportType) {
caseCriteria.setMustHaveCaseManagementData(Boolean.TRUE);
}
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<CaseExportDto> cq = cb.createQuery(CaseExportDto.class);
Root<Case> caseRoot = cq.from(Case.class);
final CaseQueryContext caseQueryContext = new CaseQueryContext(cb, cq, caseRoot);
final CaseJoins<Case> joins = (CaseJoins<Case>) caseQueryContext.getJoins();
// Events count subquery
Subquery<Long> eventCountSq = cq.subquery(Long.class);
Root<EventParticipant> eventCountRoot = eventCountSq.from(EventParticipant.class);
Join<EventParticipant, Event> event = eventCountRoot.join(EventParticipant.EVENT, JoinType.INNER);
Join<EventParticipant, Case> resultingCase = eventCountRoot.join(EventParticipant.RESULTING_CASE, JoinType.INNER);
eventCountSq.where(cb.and(cb.equal(resultingCase.get(Case.ID), caseRoot.get(Case.ID)), cb.isFalse(event.get(Event.DELETED)), cb.isFalse(event.get(Event.ARCHIVED)), cb.isFalse(eventCountRoot.get(EventParticipant.DELETED))));
eventCountSq.select(cb.countDistinct(event.get(Event.ID)));
// @formatter:off
cq.multiselect(caseRoot.get(Case.ID), joins.getPerson().get(Person.ID), joins.getPersonAddress().get(Location.ID), joins.getEpiData().get(EpiData.ID), joins.getSymptoms().get(Symptoms.ID), joins.getHospitalization().get(Hospitalization.ID), joins.getHealthConditions().get(HealthConditions.ID), caseRoot.get(Case.UUID), caseRoot.get(Case.EPID_NUMBER), caseRoot.get(Case.DISEASE), caseRoot.get(Case.DISEASE_VARIANT), caseRoot.get(Case.DISEASE_DETAILS), caseRoot.get(Case.DISEASE_VARIANT_DETAILS), joins.getPerson().get(Person.UUID), joins.getPerson().get(Person.FIRST_NAME), joins.getPerson().get(Person.LAST_NAME), joins.getPerson().get(Person.SALUTATION), joins.getPerson().get(Person.OTHER_SALUTATION), joins.getPerson().get(Person.SEX), caseRoot.get(Case.PREGNANT), joins.getPerson().get(Person.APPROXIMATE_AGE), joins.getPerson().get(Person.APPROXIMATE_AGE_TYPE), joins.getPerson().get(Person.BIRTHDATE_DD), joins.getPerson().get(Person.BIRTHDATE_MM), joins.getPerson().get(Person.BIRTHDATE_YYYY), caseRoot.get(Case.REPORT_DATE), joins.getRegion().get(Region.NAME), joins.getDistrict().get(District.NAME), joins.getCommunity().get(Community.NAME), caseRoot.get(Case.FACILITY_TYPE), joins.getFacility().get(Facility.NAME), joins.getFacility().get(Facility.UUID), caseRoot.get(Case.HEALTH_FACILITY_DETAILS), joins.getPointOfEntry().get(PointOfEntry.NAME), joins.getPointOfEntry().get(PointOfEntry.UUID), caseRoot.get(Case.POINT_OF_ENTRY_DETAILS), caseRoot.get(Case.CASE_CLASSIFICATION), caseRoot.get(Case.CLINICAL_CONFIRMATION), caseRoot.get(Case.EPIDEMIOLOGICAL_CONFIRMATION), caseRoot.get(Case.LABORATORY_DIAGNOSTIC_CONFIRMATION), caseRoot.get(Case.NOT_A_CASE_REASON_NEGATIVE_TEST), caseRoot.get(Case.NOT_A_CASE_REASON_PHYSICIAN_INFORMATION), caseRoot.get(Case.NOT_A_CASE_REASON_DIFFERENT_PATHOGEN), caseRoot.get(Case.NOT_A_CASE_REASON_OTHER), caseRoot.get(Case.NOT_A_CASE_REASON_DETAILS), caseRoot.get(Case.INVESTIGATION_STATUS), caseRoot.get(Case.INVESTIGATED_DATE), caseRoot.get(Case.OUTCOME), caseRoot.get(Case.OUTCOME_DATE), caseRoot.get(Case.SEQUELAE), caseRoot.get(Case.SEQUELAE_DETAILS), caseRoot.get(Case.BLOOD_ORGAN_OR_TISSUE_DONATED), caseRoot.get(Case.FOLLOW_UP_STATUS), caseRoot.get(Case.FOLLOW_UP_UNTIL), caseRoot.get(Case.NOSOCOMIAL_OUTBREAK), caseRoot.get(Case.INFECTION_SETTING), caseRoot.get(Case.PROHIBITION_TO_WORK), caseRoot.get(Case.PROHIBITION_TO_WORK_FROM), caseRoot.get(Case.PROHIBITION_TO_WORK_UNTIL), caseRoot.get(Case.RE_INFECTION), caseRoot.get(Case.PREVIOUS_INFECTION_DATE), caseRoot.get(Case.REINFECTION_STATUS), caseRoot.get(Case.REINFECTION_DETAILS), // quarantine
caseRoot.get(Case.QUARANTINE), caseRoot.get(Case.QUARANTINE_TYPE_DETAILS), caseRoot.get(Case.QUARANTINE_FROM), caseRoot.get(Case.QUARANTINE_TO), caseRoot.get(Case.QUARANTINE_HELP_NEEDED), caseRoot.get(Case.QUARANTINE_ORDERED_VERBALLY), caseRoot.get(Case.QUARANTINE_ORDERED_OFFICIAL_DOCUMENT), caseRoot.get(Case.QUARANTINE_ORDERED_VERBALLY_DATE), caseRoot.get(Case.QUARANTINE_ORDERED_OFFICIAL_DOCUMENT_DATE), caseRoot.get(Case.QUARANTINE_EXTENDED), caseRoot.get(Case.QUARANTINE_REDUCED), caseRoot.get(Case.QUARANTINE_OFFICIAL_ORDER_SENT), caseRoot.get(Case.QUARANTINE_OFFICIAL_ORDER_SENT_DATE), joins.getHospitalization().get(Hospitalization.ADMITTED_TO_HEALTH_FACILITY), joins.getHospitalization().get(Hospitalization.ADMISSION_DATE), joins.getHospitalization().get(Hospitalization.DISCHARGE_DATE), joins.getHospitalization().get(Hospitalization.LEFT_AGAINST_ADVICE), joins.getPerson().get(Person.PRESENT_CONDITION), joins.getPerson().get(Person.DEATH_DATE), joins.getPerson().get(Person.BURIAL_DATE), joins.getPerson().get(Person.BURIAL_CONDUCTOR), joins.getPerson().get(Person.BURIAL_PLACE_DESCRIPTION), // address
joins.getPersonAddressRegion().get(Region.NAME), joins.getPersonAddressDistrict().get(District.NAME), joins.getPersonAddressCommunity().get(Community.NAME), joins.getPersonAddress().get(Location.CITY), joins.getPersonAddress().get(Location.STREET), joins.getPersonAddress().get(Location.HOUSE_NUMBER), joins.getPersonAddress().get(Location.ADDITIONAL_INFORMATION), joins.getPersonAddress().get(Location.POSTAL_CODE), joins.getPersonAddressFacility().get(Facility.NAME), joins.getPersonAddressFacility().get(Facility.UUID), joins.getPersonAddress().get(Location.FACILITY_DETAILS), // phone
caseQueryContext.getSubqueryExpression(CaseQueryContext.PERSON_PHONE_SUBQUERY), caseQueryContext.getSubqueryExpression(CaseQueryContext.PERSON_PHONE_OWNER_SUBQUERY), caseQueryContext.getSubqueryExpression(CaseQueryContext.PERSON_EMAIL_SUBQUERY), caseQueryContext.getSubqueryExpression(CaseQueryContext.PERSON_OTHER_CONTACT_DETAILS_SUBQUERY), joins.getPerson().get(Person.EDUCATION_TYPE), joins.getPerson().get(Person.EDUCATION_DETAILS), joins.getPerson().get(Person.OCCUPATION_TYPE), joins.getPerson().get(Person.OCCUPATION_DETAILS), joins.getPerson().get(Person.ARMED_FORCES_RELATION_TYPE), joins.getEpiData().get(EpiData.CONTACT_WITH_SOURCE_CASE_KNOWN), caseRoot.get(Case.VACCINATION_STATUS), caseRoot.get(Case.POSTPARTUM), caseRoot.get(Case.TRIMESTER), eventCountSq, caseRoot.get(Case.EXTERNAL_ID), caseRoot.get(Case.EXTERNAL_TOKEN), caseRoot.get(Case.INTERNAL_TOKEN), joins.getPerson().get(Person.BIRTH_NAME), joins.getPersonBirthCountry().get(Country.ISO_CODE), joins.getPersonBirthCountry().get(Country.DEFAULT_NAME), joins.getPersonCitizenship().get(Country.ISO_CODE), joins.getPersonCitizenship().get(Country.DEFAULT_NAME), caseRoot.get(Case.CASE_IDENTIFICATION_SOURCE), caseRoot.get(Case.SCREENING_TYPE), // responsible jurisdiction
joins.getResponsibleRegion().get(Region.NAME), joins.getResponsibleDistrict().get(District.NAME), joins.getResponsibleCommunity().get(Community.NAME), caseRoot.get(Case.CLINICIAN_NAME), caseRoot.get(Case.CLINICIAN_PHONE), caseRoot.get(Case.CLINICIAN_EMAIL), joins.getReportingUser().get(User.ID), joins.getFollowUpStatusChangeUser().get(User.ID), caseRoot.get(Case.PREVIOUS_QUARANTINE_TO), caseRoot.get(Case.QUARANTINE_CHANGE_COMMENT), JurisdictionHelper.booleanSelector(cb, service.inJurisdictionOrOwned(caseQueryContext)));
// @formatter:on
cq.distinct(true);
Predicate filter = service.createUserFilter(cb, cq, caseRoot);
if (caseCriteria != null) {
Predicate criteriaFilter = service.createCriteriaFilter(caseCriteria, caseQueryContext);
filter = CriteriaBuilderHelper.and(cb, filter, criteriaFilter);
}
filter = CriteriaBuilderHelper.andInValues(selectedRows, filter, cb, caseRoot.get(Case.UUID));
if (filter != null) {
cq.where(filter);
}
/*
* Sort by report date DESC, but also by id for stable Sorting in case of equal report dates.
* Since this method supports paging, values might jump between pages when sorting is unstable.
*/
cq.orderBy(cb.desc(caseRoot.get(Case.REPORT_DATE)), cb.desc(caseRoot.get(Case.ID)));
List<CaseExportDto> resultList = QueryHelper.getResultList(em, cq, first, max);
List<Long> resultCaseIds = resultList.stream().map(CaseExportDto::getId).collect(Collectors.toList());
if (!resultList.isEmpty()) {
Map<Long, Symptoms> symptoms = null;
if (ExportHelper.shouldExportFields(exportConfiguration, CaseDataDto.SYMPTOMS)) {
List<Symptoms> symptomsList = null;
CriteriaQuery<Symptoms> symptomsCq = cb.createQuery(Symptoms.class);
Root<Symptoms> symptomsRoot = symptomsCq.from(Symptoms.class);
Expression<String> symptomsIdsExpr = symptomsRoot.get(Symptoms.ID);
symptomsCq.where(symptomsIdsExpr.in(resultList.stream().map(CaseExportDto::getSymptomsId).collect(Collectors.toList())));
symptomsList = em.createQuery(symptomsCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
symptoms = symptomsList.stream().collect(Collectors.toMap(Symptoms::getId, Function.identity()));
}
Map<Long, Location> personAddresses = null;
if (ExportHelper.shouldExportFields(exportConfiguration, PersonDto.ADDRESS, CaseExportDto.ADDRESS_GPS_COORDINATES)) {
CriteriaQuery<Location> personAddressesCq = cb.createQuery(Location.class);
Root<Location> personAddressesRoot = personAddressesCq.from(Location.class);
Expression<String> personAddressesIdsExpr = personAddressesRoot.get(Location.ID);
personAddressesCq.where(personAddressesIdsExpr.in(resultList.stream().map(CaseExportDto::getPersonAddressId).collect(Collectors.toList())));
List<Location> personAddressesList = em.createQuery(personAddressesCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
personAddresses = personAddressesList.stream().collect(Collectors.toMap(Location::getId, Function.identity()));
}
Map<Long, Integer> prescriptionCounts = null;
Map<Long, Integer> treatmentCounts = null;
Map<Long, Integer> clinicalVisitCounts = null;
Map<Long, HealthConditions> healthConditions = null;
if (exportType == null || exportType == CaseExportType.CASE_MANAGEMENT) {
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.NUMBER_OF_PRESCRIPTIONS)) {
prescriptionCounts = prescriptionService.getPrescriptionCountByCases(resultCaseIds).stream().collect(Collectors.toMap(e -> (Long) e[0], e -> ((Long) e[1]).intValue()));
}
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.NUMBER_OF_TREATMENTS)) {
treatmentCounts = treatmentService.getTreatmentCountByCases(resultCaseIds).stream().collect(Collectors.toMap(e -> (Long) e[0], e -> ((Long) e[1]).intValue()));
}
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.NUMBER_OF_CLINICAL_VISITS)) {
clinicalVisitCounts = clinicalVisitService.getClinicalVisitCountByCases(resultCaseIds).stream().collect(Collectors.toMap(e -> (Long) e[0], e -> ((Long) e[1]).intValue()));
}
if (ExportHelper.shouldExportFields(exportConfiguration, CaseDataDto.HEALTH_CONDITIONS)) {
List<HealthConditions> healthConditionsList = null;
CriteriaQuery<HealthConditions> healthConditionsCq = cb.createQuery(HealthConditions.class);
Root<HealthConditions> healthConditionsRoot = healthConditionsCq.from(HealthConditions.class);
Expression<String> healthConditionsIdsExpr = healthConditionsRoot.get(HealthConditions.ID);
healthConditionsCq.where(healthConditionsIdsExpr.in(resultList.stream().map(CaseExportDto::getHealthConditionsId).collect(Collectors.toList())));
healthConditionsList = em.createQuery(healthConditionsCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
healthConditions = healthConditionsList.stream().collect(Collectors.toMap(HealthConditions::getId, Function.identity()));
}
}
Map<Long, PreviousHospitalization> firstPreviousHospitalizations = null;
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.INITIAL_DETECTION_PLACE)) {
List<PreviousHospitalization> prevHospsList = null;
CriteriaQuery<PreviousHospitalization> prevHospsCq = cb.createQuery(PreviousHospitalization.class);
Root<PreviousHospitalization> prevHospsRoot = prevHospsCq.from(PreviousHospitalization.class);
Join<PreviousHospitalization, Hospitalization> prevHospsHospitalizationJoin = prevHospsRoot.join(PreviousHospitalization.HOSPITALIZATION, JoinType.LEFT);
Expression<String> hospitalizationIdsExpr = prevHospsHospitalizationJoin.get(Hospitalization.ID);
prevHospsCq.where(hospitalizationIdsExpr.in(resultList.stream().map(CaseExportDto::getHospitalizationId).collect(Collectors.toList())));
prevHospsCq.orderBy(cb.asc(prevHospsRoot.get(PreviousHospitalization.ADMISSION_DATE)));
prevHospsList = em.createQuery(prevHospsCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
firstPreviousHospitalizations = prevHospsList.stream().collect(Collectors.toMap(p -> p.getHospitalization().getId(), Function.identity(), (id1, id2) -> id1));
}
Map<Long, CaseClassification> sourceCaseClassifications = null;
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.MAX_SOURCE_CASE_CLASSIFICATION)) {
sourceCaseClassifications = contactService.getSourceCaseClassifications(resultCaseIds).stream().collect(Collectors.toMap(e -> (Long) e[0], e -> (CaseClassification) e[1], (c1, c2) -> c1.getSeverity() >= c2.getSeverity() ? c1 : c2));
}
List<Long> caseIdsWithOutbreak = null;
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.ASSOCIATED_WITH_OUTBREAK)) {
caseIdsWithOutbreak = outbreakService.getCaseIdsWithOutbreak(resultCaseIds);
}
Map<Long, List<Exposure>> exposures = null;
if ((exportType == null || exportType == CaseExportType.CASE_SURVEILLANCE) && ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.TRAVELED, CaseExportDto.TRAVEL_HISTORY, CaseExportDto.BURIAL_ATTENDED)) {
CriteriaQuery<Exposure> exposuresCq = cb.createQuery(Exposure.class);
Root<Exposure> exposuresRoot = exposuresCq.from(Exposure.class);
Join<Exposure, EpiData> exposuresEpiDataJoin = exposuresRoot.join(Exposure.EPI_DATA, JoinType.LEFT);
Expression<String> epiDataIdsExpr = exposuresEpiDataJoin.get(EpiData.ID);
Predicate exposuresPredicate = cb.and(epiDataIdsExpr.in(resultList.stream().map(CaseExportDto::getEpiDataId).collect(Collectors.toList())), cb.or(cb.equal(exposuresRoot.get(Exposure.EXPOSURE_TYPE), ExposureType.TRAVEL), cb.equal(exposuresRoot.get(Exposure.EXPOSURE_TYPE), ExposureType.BURIAL)));
exposuresCq.where(exposuresPredicate);
exposuresCq.orderBy(cb.asc(exposuresEpiDataJoin.get(EpiData.ID)));
List<Exposure> exposureList = em.createQuery(exposuresCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
exposures = exposureList.stream().collect(Collectors.groupingBy(e -> e.getEpiData().getId()));
}
Map<Long, List<Sample>> samples = null;
if ((exportType == null || exportType == CaseExportType.CASE_SURVEILLANCE) && ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.SAMPLE_INFORMATION)) {
List<Sample> samplesList = null;
CriteriaQuery<Sample> samplesCq = cb.createQuery(Sample.class);
Root<Sample> samplesRoot = samplesCq.from(Sample.class);
Join<Sample, Case> samplesCaseJoin = samplesRoot.join(Sample.ASSOCIATED_CASE, JoinType.LEFT);
Expression<String> caseIdsExpr = samplesCaseJoin.get(Case.ID);
samplesCq.where(caseIdsExpr.in(resultCaseIds));
samplesList = em.createQuery(samplesCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
samples = samplesList.stream().collect(Collectors.groupingBy(s -> s.getAssociatedCase().getId()));
}
List<VisitSummaryExportDetails> visitSummaries = null;
if (featureConfigurationFacade.isFeatureEnabled(FeatureType.CASE_FOLLOWUP) && ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.NUMBER_OF_VISITS, CaseExportDto.LAST_COOPERATIVE_VISIT_DATE, CaseExportDto.LAST_COOPERATIVE_VISIT_SYMPTOMATIC, CaseExportDto.LAST_COOPERATIVE_VISIT_SYMPTOMS)) {
CriteriaQuery<VisitSummaryExportDetails> visitsCq = cb.createQuery(VisitSummaryExportDetails.class);
Root<Case> visitsCqRoot = visitsCq.from(Case.class);
Join<Case, Visit> visitsJoin = visitsCqRoot.join(Case.VISITS, JoinType.LEFT);
Join<Visit, Symptoms> visitSymptomsJoin = visitsJoin.join(Visit.SYMPTOMS, JoinType.LEFT);
visitsCq.where(CriteriaBuilderHelper.and(cb, visitsCqRoot.get(AbstractDomainObject.ID).in(resultCaseIds), cb.isNotEmpty(visitsCqRoot.get(Case.VISITS))));
visitsCq.multiselect(visitsCqRoot.get(AbstractDomainObject.ID), visitsJoin.get(Visit.VISIT_DATE_TIME), visitsJoin.get(Visit.VISIT_STATUS), visitSymptomsJoin);
visitSummaries = em.createQuery(visitsCq).getResultList();
}
Map<Long, List<Immunization>> immunizations = null;
if ((exportType == null || exportType == CaseExportType.CASE_SURVEILLANCE) && (exportConfiguration == null || exportConfiguration.getProperties().stream().anyMatch(p -> StringUtils.equalsAny(p, ExportHelper.getVaccinationExportProperties())))) {
List<Immunization> immunizationList;
CriteriaQuery<Immunization> immunizationsCq = cb.createQuery(Immunization.class);
Root<Immunization> immunizationsCqRoot = immunizationsCq.from(Immunization.class);
Join<Immunization, Person> personJoin = immunizationsCqRoot.join(Immunization.PERSON, JoinType.LEFT);
Expression<String> personIdsExpr = personJoin.get(Person.ID);
immunizationsCq.where(CriteriaBuilderHelper.and(cb, cb.or(cb.equal(immunizationsCqRoot.get(Immunization.MEANS_OF_IMMUNIZATION), MeansOfImmunization.VACCINATION), cb.equal(immunizationsCqRoot.get(Immunization.MEANS_OF_IMMUNIZATION), MeansOfImmunization.VACCINATION_RECOVERY)), personIdsExpr.in(resultList.stream().map(CaseExportDto::getPersonId).collect(Collectors.toList()))));
immunizationsCq.select(immunizationsCqRoot);
immunizationList = em.createQuery(immunizationsCq).setHint(ModelConstants.HINT_HIBERNATE_READ_ONLY, true).getResultList();
immunizations = immunizationList.stream().collect(Collectors.groupingBy(i -> i.getPerson().getId()));
}
// Load latest events info
// Adding a second query here is not perfect, but selecting the last event with a criteria query
// doesn't seem to be possible and using a native query is not an option because of user filters
List<EventSummaryDetails> eventSummaries = null;
if (ExportHelper.shouldExportFields(exportConfiguration, CaseExportDto.LATEST_EVENT_ID, CaseExportDto.LATEST_EVENT_STATUS, CaseExportDto.LATEST_EVENT_TITLE)) {
eventSummaries = eventService.getEventSummaryDetailsByCases(resultCaseIds);
}
Map<Long, UserReference> caseUsers = getCaseUsersForExport(resultList, exportConfiguration);
Pseudonymizer pseudonymizer = Pseudonymizer.getDefault(userService::hasRight, I18nProperties.getCaption(Captions.inaccessibleValue));
for (CaseExportDto exportDto : resultList) {
final boolean inJurisdiction = exportDto.getInJurisdiction();
if (exportConfiguration == null || exportConfiguration.getProperties().contains(CaseExportDto.COUNTRY)) {
exportDto.setCountry(configFacade.getEpidPrefix());
}
if (symptoms != null) {
Optional.ofNullable(symptoms.get(exportDto.getSymptomsId())).ifPresent(symptom -> exportDto.setSymptoms(SymptomsFacadeEjb.toDto(symptom)));
}
if (personAddresses != null || exportConfiguration.getProperties().contains(CaseExportDto.ADDRESS_GPS_COORDINATES)) {
Optional.ofNullable(personAddresses.get(exportDto.getPersonAddressId())).ifPresent(personAddress -> exportDto.setAddressGpsCoordinates(personAddress.buildGpsCoordinatesCaption()));
}
if (prescriptionCounts != null) {
Optional.ofNullable(prescriptionCounts.get(exportDto.getId())).ifPresent(prescriptionCount -> exportDto.setNumberOfPrescriptions(prescriptionCount));
}
if (treatmentCounts != null) {
Optional.ofNullable(treatmentCounts.get(exportDto.getId())).ifPresent(treatmentCount -> exportDto.setNumberOfTreatments(treatmentCount));
}
if (clinicalVisitCounts != null) {
Optional.ofNullable(clinicalVisitCounts.get(exportDto.getId())).ifPresent(clinicalVisitCount -> exportDto.setNumberOfClinicalVisits(clinicalVisitCount));
}
if (healthConditions != null) {
Optional.ofNullable(healthConditions.get(exportDto.getHealthConditionsId())).ifPresent(healthCondition -> exportDto.setHealthConditions(healthConditionsMapper.toDto(healthCondition)));
}
if (firstPreviousHospitalizations != null) {
Optional.ofNullable(firstPreviousHospitalizations.get(exportDto.getHospitalizationId())).ifPresent(firstPreviousHospitalization -> {
if (firstPreviousHospitalization.getHealthFacility() != null) {
exportDto.setInitialDetectionPlace(FacilityHelper.buildFacilityString(firstPreviousHospitalization.getHealthFacility().getUuid(), firstPreviousHospitalization.getHealthFacility().getName(), firstPreviousHospitalization.getHealthFacilityDetails()));
} else {
exportDto.setInitialDetectionPlace(I18nProperties.getCaption(Captions.unknown));
}
});
if (StringUtils.isEmpty(exportDto.getInitialDetectionPlace())) {
if (!StringUtils.isEmpty(exportDto.getHealthFacility())) {
exportDto.setInitialDetectionPlace(exportDto.getHealthFacility());
} else {
exportDto.setInitialDetectionPlace(exportDto.getPointOfEntry());
}
}
}
if (sourceCaseClassifications != null) {
Optional.ofNullable(sourceCaseClassifications.get(exportDto.getId())).ifPresent(sourceCaseClassification -> exportDto.setMaxSourceCaseClassification(sourceCaseClassification));
}
if (caseIdsWithOutbreak != null) {
exportDto.setAssociatedWithOutbreak(caseIdsWithOutbreak.contains(exportDto.getId()));
}
if (exposures != null) {
Optional.ofNullable(exposures.get(exportDto.getEpiDataId())).ifPresent(caseExposures -> {
StringBuilder travelHistoryBuilder = new StringBuilder();
if (caseExposures.stream().anyMatch(e -> ExposureType.BURIAL.equals(e.getExposureType()))) {
exportDto.setBurialAttended(true);
}
caseExposures.stream().filter(e -> ExposureType.TRAVEL.equals(e.getExposureType())).forEach(exposure -> travelHistoryBuilder.append(EpiDataHelper.buildDetailedTravelString(exposure.getLocation().toString(), exposure.getDescription(), exposure.getStartDate(), exposure.getEndDate(), userLanguage)).append(", "));
if (travelHistoryBuilder.length() > 0) {
exportDto.setTraveled(true);
travelHistoryBuilder.delete(travelHistoryBuilder.lastIndexOf(", "), travelHistoryBuilder.length() - 1);
}
exportDto.setTravelHistory(travelHistoryBuilder.toString());
});
}
if (samples != null) {
Optional.ofNullable(samples.get(exportDto.getId())).ifPresent(caseSamples -> {
int count = 0;
caseSamples.sort((o1, o2) -> o2.getSampleDateTime().compareTo(o1.getSampleDateTime()));
for (Sample sample : caseSamples) {
EmbeddedSampleExportDto sampleDto = new EmbeddedSampleExportDto(sample.getUuid(), sample.getSampleDateTime(), sample.getLab() != null ? FacilityHelper.buildFacilityString(sample.getLab().getUuid(), sample.getLab().getName(), sample.getLabDetails()) : null, sample.getPathogenTestResult());
switch(++count) {
case 1:
exportDto.setSample1(sampleDto);
break;
case 2:
exportDto.setSample2(sampleDto);
break;
case 3:
exportDto.setSample3(sampleDto);
break;
default:
exportDto.addOtherSample(sampleDto);
}
}
});
}
if (immunizations != null) {
Optional.ofNullable(immunizations.get(exportDto.getPersonId())).ifPresent(caseImmunizations -> {
List<Immunization> filteredImmunizations = caseImmunizations.stream().filter(i -> i.getDisease() == exportDto.getDisease()).collect(Collectors.toList());
if (!filteredImmunizations.isEmpty()) {
filteredImmunizations.sort(Comparator.comparing(i -> ImmunizationEntityHelper.getDateForComparison(i, false)));
Immunization mostRecentImmunization = filteredImmunizations.get(filteredImmunizations.size() - 1);
Integer numberOfDoses = mostRecentImmunization.getNumberOfDoses();
exportDto.setNumberOfDoses(numberOfDoses != null ? String.valueOf(numberOfDoses) : "");
if (CollectionUtils.isNotEmpty(mostRecentImmunization.getVaccinations())) {
List<Vaccination> sortedVaccinations = mostRecentImmunization.getVaccinations().stream().sorted(Comparator.comparing(ImmunizationEntityHelper::getVaccinationDateForComparison)).collect(Collectors.toList());
Vaccination firstVaccination = sortedVaccinations.get(0);
Vaccination lastVaccination = sortedVaccinations.get(sortedVaccinations.size() - 1);
exportDto.setFirstVaccinationDate(firstVaccination.getVaccinationDate());
exportDto.setLastVaccinationDate(lastVaccination.getVaccinationDate());
exportDto.setVaccineName(lastVaccination.getVaccineName());
exportDto.setOtherVaccineName(lastVaccination.getOtherVaccineName());
exportDto.setVaccineManufacturer(lastVaccination.getVaccineManufacturer());
exportDto.setOtherVaccineManufacturer(lastVaccination.getOtherVaccineManufacturer());
exportDto.setVaccinationInfoSource(lastVaccination.getVaccinationInfoSource());
exportDto.setVaccineAtcCode(lastVaccination.getVaccineAtcCode());
exportDto.setVaccineBatchNumber(lastVaccination.getVaccineBatchNumber());
exportDto.setVaccineUniiCode(lastVaccination.getVaccineUniiCode());
exportDto.setVaccineInn(lastVaccination.getVaccineInn());
}
}
});
}
if (visitSummaries != null) {
List<VisitSummaryExportDetails> visits = visitSummaries.stream().filter(v -> v.getContactId() == exportDto.getId()).collect(Collectors.toList());
VisitSummaryExportDetails lastCooperativeVisit = visits.stream().filter(v -> v.getVisitStatus() == VisitStatus.COOPERATIVE).max(Comparator.comparing(VisitSummaryExportDetails::getVisitDateTime)).orElse(null);
exportDto.setNumberOfVisits(visits.size());
if (lastCooperativeVisit != null) {
exportDto.setLastCooperativeVisitDate(lastCooperativeVisit.getVisitDateTime());
SymptomsDto visitSymptoms = SymptomsFacadeEjb.toDto(lastCooperativeVisit.getSymptoms());
pseudonymizer.pseudonymizeDto(SymptomsDto.class, visitSymptoms, inJurisdiction, null);
exportDto.setLastCooperativeVisitSymptoms(SymptomsHelper.buildSymptomsHumanString(visitSymptoms, true, userLanguage));
exportDto.setLastCooperativeVisitSymptomatic(visitSymptoms.getSymptomatic() == null ? YesNoUnknown.UNKNOWN : (visitSymptoms.getSymptomatic() ? YesNoUnknown.YES : YesNoUnknown.NO));
}
}
if (eventSummaries != null && exportDto.getEventCount() != 0) {
eventSummaries.stream().filter(v -> v.getCaseId() == exportDto.getId()).max(Comparator.comparing(EventSummaryDetails::getEventDate)).ifPresent(eventSummary -> {
exportDto.setLatestEventId(eventSummary.getEventUuid());
exportDto.setLatestEventStatus(eventSummary.getEventStatus());
exportDto.setLatestEventTitle(eventSummary.getEventTitle());
});
}
if (!caseUsers.isEmpty()) {
if (exportDto.getReportingUserId() != null) {
UserReference user = caseUsers.get(exportDto.getReportingUserId());
exportDto.setReportingUserName(user.getName());
exportDto.setReportingUserRoles(user.getUserRoles());
}
if (exportDto.getFollowUpStatusChangeUserId() != null) {
UserReference user = caseUsers.get(exportDto.getFollowUpStatusChangeUserId());
exportDto.setFollowUpStatusChangeUserName(user.getName());
exportDto.setFollowUpStatusChangeUserRoles(user.getUserRoles());
}
}
pseudonymizer.pseudonymizeDto(CaseExportDto.class, exportDto, inJurisdiction, c -> {
pseudonymizer.pseudonymizeDto(BirthDateDto.class, c.getBirthdate(), inJurisdiction, null);
pseudonymizer.pseudonymizeDto(EmbeddedSampleExportDto.class, c.getSample1(), inJurisdiction, null);
pseudonymizer.pseudonymizeDto(EmbeddedSampleExportDto.class, c.getSample2(), inJurisdiction, null);
pseudonymizer.pseudonymizeDto(EmbeddedSampleExportDto.class, c.getSample3(), inJurisdiction, null);
pseudonymizer.pseudonymizeDtoCollection(EmbeddedSampleExportDto.class, c.getOtherSamples(), s -> inJurisdiction, null);
pseudonymizer.pseudonymizeDto(BurialInfoDto.class, c.getBurialInfo(), inJurisdiction, null);
pseudonymizer.pseudonymizeDto(SymptomsDto.class, c.getSymptoms(), inJurisdiction, null);
});
}
}
caseCriteria.setMustHaveCaseManagementData(previousCaseManagementDataCriteria);
return resultList;
}
use of de.symeda.sormas.api.caze.CaseCriteria in project SORMAS-Project by hzi-braunschweig.
the class CaseService method getCasesForDuplicateMerging.
public List<CaseIndexDto[]> getCasesForDuplicateMerging(CaseCriteria criteria, boolean ignoreRegion, double nameSimilarityThreshold) {
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);
Root<Case> root = cq.from(Case.class);
final CaseQueryContext caseQueryContext = new CaseQueryContext(cb, cq, root);
final CaseJoins<Case> joins = (CaseJoins<Case>) caseQueryContext.getJoins();
Root<Case> root2 = cq.from(Case.class);
Join<Case, Person> person = joins.getPerson();
Join<Case, Person> person2 = root2.join(Case.PERSON, JoinType.LEFT);
Join<Case, Region> responsibleRegion = joins.getResponsibleRegion();
Join<Case, Region> responsibleRegion2 = root2.join(Case.RESPONSIBLE_REGION, JoinType.LEFT);
Join<Case, Region> region = joins.getRegion();
Join<Case, Region> region2 = root2.join(Case.REGION, JoinType.LEFT);
Join<Case, Symptoms> symptoms = joins.getSymptoms();
Join<Case, Symptoms> symptoms2 = root2.join(Case.SYMPTOMS, JoinType.LEFT);
cq.distinct(true);
// similarity:
// * first & last name concatenated with whitespace. Similarity function with default threshold of 0.65D
// uses postgres pg_trgm: https://www.postgresql.org/docs/9.6/pgtrgm.html
// * same disease
// * same region (optional)
// * report date within 30 days of each other
// * same sex or same birth date (when defined)
// * same birth date (when fully defined)
// * onset date within 30 days of each other (when defined)
Predicate userFilter = createUserFilter(cb, cq, root);
Predicate criteriaFilter = criteria != null ? createCriteriaFilter(criteria, caseQueryContext) : null;
Expression<String> nameSimilarityExpr = cb.concat(person.get(Person.FIRST_NAME), " ");
nameSimilarityExpr = cb.concat(nameSimilarityExpr, person.get(Person.LAST_NAME));
Expression<String> nameSimilarityExpr2 = cb.concat(person2.get(Person.FIRST_NAME), " ");
nameSimilarityExpr2 = cb.concat(nameSimilarityExpr2, person2.get(Person.LAST_NAME));
Predicate nameSimilarityFilter = cb.gt(cb.function("similarity", double.class, nameSimilarityExpr, nameSimilarityExpr2), nameSimilarityThreshold);
Predicate diseaseFilter = cb.equal(root.get(Case.DISEASE), root2.get(Case.DISEASE));
Predicate regionFilter = cb.and(cb.equal(responsibleRegion.get(Region.ID), responsibleRegion2.get(Region.ID)), cb.or(cb.and(cb.isNull(region)), cb.equal(region.get(Region.ID), region2.get(Region.ID))));
Predicate reportDateFilter = cb.lessThanOrEqualTo(cb.abs(cb.diff(cb.function("date_part", Long.class, cb.parameter(String.class, "date_type"), root.get(Case.REPORT_DATE)), cb.function("date_part", Long.class, cb.parameter(String.class, "date_type"), root2.get(Case.REPORT_DATE)))), SECONDS_30_DAYS);
// // todo this should use PersonService.buildSimilarityCriteriaFilter
// Sex filter: only when sex is filled in for both cases
Predicate sexFilter = cb.or(cb.or(cb.isNull(person.get(Person.SEX)), cb.isNull(person2.get(Person.SEX))), cb.or(cb.equal(person.get(Person.SEX), Sex.UNKNOWN), cb.equal(person2.get(Person.SEX), Sex.UNKNOWN)), cb.equal(person.get(Person.SEX), person2.get(Person.SEX)));
// Birth date filter: only when birth date is filled in for both cases
Predicate birthDateFilter = cb.or(cb.or(cb.isNull(person.get(Person.BIRTHDATE_DD)), cb.isNull(person.get(Person.BIRTHDATE_MM)), cb.isNull(person.get(Person.BIRTHDATE_YYYY)), cb.isNull(person2.get(Person.BIRTHDATE_DD)), cb.isNull(person2.get(Person.BIRTHDATE_MM)), cb.isNull(person2.get(Person.BIRTHDATE_YYYY))), cb.and(cb.equal(person.get(Person.BIRTHDATE_DD), person2.get(Person.BIRTHDATE_DD)), cb.equal(person.get(Person.BIRTHDATE_MM), person2.get(Person.BIRTHDATE_MM)), cb.equal(person.get(Person.BIRTHDATE_YYYY), person2.get(Person.BIRTHDATE_YYYY))));
// Onset date filter: only when onset date is filled in for both cases
Predicate onsetDateFilter = cb.or(cb.or(cb.isNull(symptoms.get(Symptoms.ONSET_DATE)), cb.isNull(symptoms2.get(Symptoms.ONSET_DATE))), cb.lessThanOrEqualTo(cb.abs(cb.diff(cb.function("date_part", Long.class, cb.parameter(String.class, "date_type"), symptoms.get(Symptoms.ONSET_DATE)), cb.function("date_part", Long.class, cb.parameter(String.class, "date_type"), symptoms2.get(Symptoms.ONSET_DATE)))), SECONDS_30_DAYS));
Predicate creationDateFilter = cb.or(cb.lessThan(root.get(Case.CREATION_DATE), root2.get(Case.CREATION_DATE)), cb.or(cb.lessThanOrEqualTo(root2.get(Case.CREATION_DATE), DateHelper.getStartOfDay(criteria.getCreationDateFrom())), cb.greaterThanOrEqualTo(root2.get(Case.CREATION_DATE), DateHelper.getEndOfDay(criteria.getCreationDateTo()))));
Predicate filter = cb.and(createDefaultFilter(cb, root), createDefaultFilter(cb, root2));
if (userFilter != null) {
filter = cb.and(filter, userFilter);
}
if (filter != null) {
filter = cb.and(filter, criteriaFilter);
} else {
filter = criteriaFilter;
}
if (filter != null) {
filter = cb.and(filter, nameSimilarityFilter);
} else {
filter = nameSimilarityFilter;
}
filter = cb.and(filter, diseaseFilter);
if (!ignoreRegion) {
filter = cb.and(filter, regionFilter);
}
filter = cb.and(filter, reportDateFilter);
filter = cb.and(filter, cb.and(sexFilter, birthDateFilter));
filter = cb.and(filter, onsetDateFilter);
filter = cb.and(filter, creationDateFilter);
filter = cb.and(filter, cb.notEqual(root.get(Case.ID), root2.get(Case.ID)));
cq.where(filter);
cq.multiselect(root.get(Case.ID), root2.get(Case.ID), root.get(Case.CREATION_DATE));
cq.orderBy(cb.desc(root.get(Case.CREATION_DATE)));
List<Object[]> foundIds = em.createQuery(cq).setParameter("date_type", "epoch").getResultList();
List<CaseIndexDto[]> resultList = new ArrayList<>();
if (!foundIds.isEmpty()) {
CriteriaQuery<CaseIndexDto> indexCasesCq = cb.createQuery(CaseIndexDto.class);
Root<Case> indexRoot = indexCasesCq.from(Case.class);
selectIndexDtoFields(new CaseQueryContext(cb, indexCasesCq, indexRoot));
indexCasesCq.where(indexRoot.get(Case.ID).in(foundIds.stream().map(a -> Arrays.copyOf(a, 2)).flatMap(Arrays::stream).collect(Collectors.toSet())));
Map<Long, CaseIndexDto> indexCases = em.createQuery(indexCasesCq).getResultStream().collect(Collectors.toMap(c -> c.getId(), Function.identity()));
for (Object[] idPair : foundIds) {
try {
// Cloning is necessary here to allow us to add the same CaseIndexDto to the grid multiple times
CaseIndexDto parent = (CaseIndexDto) indexCases.get(idPair[0]).clone();
CaseIndexDto child = (CaseIndexDto) indexCases.get(idPair[1]).clone();
if (parent.getCompleteness() == null && child.getCompleteness() == null || parent.getCompleteness() != null && (child.getCompleteness() == null || (parent.getCompleteness() >= child.getCompleteness()))) {
resultList.add(new CaseIndexDto[] { parent, child });
} else {
resultList.add(new CaseIndexDto[] { child, parent });
}
} catch (CloneNotSupportedException e) {
throw new RuntimeException(e);
}
}
}
return resultList;
}
use of de.symeda.sormas.api.caze.CaseCriteria in project SORMAS-Project by hzi-braunschweig.
the class CaseFacadeEjbTest method testGetDuplicateCasesOfSameSexAndDifferentBirthDateIsEmpty.
@Test
public void testGetDuplicateCasesOfSameSexAndDifferentBirthDateIsEmpty() {
final Date today = new Date();
RDCFEntities rdcf = creator.createRDCFEntities("Region", "District", "Community", "Facility");
UserDto user = creator.createUser(rdcf.region.getUuid(), rdcf.district.getUuid(), rdcf.facility.getUuid(), "Surv", "Sup", UserRole.SURVEILLANCE_SUPERVISOR);
PersonDto cazePerson = creator.createPerson("Case", "Person", Sex.MALE, 1980, 1, 1);
creator.createCase(user.toReference(), cazePerson.toReference(), Disease.EVD, CaseClassification.PROBABLE, InvestigationStatus.PENDING, today, rdcf);
PersonDto cazePerson2 = creator.createPerson("Case", "Person", Sex.MALE, 1980, 1, 2);
creator.createCase(user.toReference(), cazePerson2.toReference(), Disease.EVD, CaseClassification.PROBABLE, InvestigationStatus.PENDING, DateUtils.addMinutes(today, -3), rdcf);
Assert.assertEquals(0, getCaseFacade().getCasesForDuplicateMerging(new CaseCriteria().creationDateFrom(today).creationDateTo(today), true).size());
}
use of de.symeda.sormas.api.caze.CaseCriteria in project SORMAS-Project by hzi-braunschweig.
the class CaseFacadeEjbTest method testGetDuplicateCasesOfSexUnknownAndSameBirthDateMatches.
@Test
public void testGetDuplicateCasesOfSexUnknownAndSameBirthDateMatches() {
final Date today = new Date();
RDCFEntities rdcf = creator.createRDCFEntities("Region", "District", "Community", "Facility");
UserDto user = creator.createUser(rdcf.region.getUuid(), rdcf.district.getUuid(), rdcf.facility.getUuid(), "Surv", "Sup", UserRole.SURVEILLANCE_SUPERVISOR);
PersonDto cazePerson = creator.createPerson("Case", "Person", Sex.MALE, 1980, 1, 1);
creator.createCase(user.toReference(), cazePerson.toReference(), Disease.EVD, CaseClassification.PROBABLE, InvestigationStatus.PENDING, today, rdcf);
PersonDto cazePerson2 = creator.createPerson("Case", "Person", Sex.UNKNOWN, 1980, 1, 1);
creator.createCase(user.toReference(), cazePerson2.toReference(), Disease.EVD, CaseClassification.PROBABLE, InvestigationStatus.PENDING, DateUtils.addMinutes(today, -3), rdcf);
Assert.assertEquals(1, getCaseFacade().getCasesForDuplicateMerging(new CaseCriteria().creationDateFrom(today).creationDateTo(today), true).size());
}
Aggregations