Search in sources :

Example 1 with Treatment

use of de.symeda.sormas.backend.therapy.Treatment in project SORMAS-Project by hzi-braunschweig.

the class CaseFacadeEjb method mergeCase.

private void mergeCase(CaseDataDto leadCaseData, CaseDataDto otherCaseData, boolean cloning) {
    // 1 Merge Dtos
    // 1.1 Case
    copyDtoValues(leadCaseData, otherCaseData, cloning);
    save(leadCaseData, !cloning, true, true, false);
    // 1.2 Person - Only merge when the persons have different UUIDs
    if (!cloning && !DataHelper.equal(leadCaseData.getPerson().getUuid(), otherCaseData.getPerson().getUuid())) {
        PersonDto leadPerson = personFacade.getPersonByUuid(leadCaseData.getPerson().getUuid());
        PersonDto otherPerson = personFacade.getPersonByUuid(otherCaseData.getPerson().getUuid());
        personFacade.mergePerson(leadPerson, otherPerson);
    } else {
        assert (DataHelper.equal(leadCaseData.getPerson().getUuid(), otherCaseData.getPerson().getUuid()));
    }
    // 2 Change CaseReference
    Case leadCase = service.getByUuid(leadCaseData.getUuid());
    Case otherCase = service.getByUuid(otherCaseData.getUuid());
    // 2.1 Contacts
    List<Contact> contacts = contactService.findBy(new ContactCriteria().caze(otherCase.toReference()), null);
    for (Contact contact : contacts) {
        if (cloning) {
            ContactDto newContact = ContactDto.build(leadCase.toReference(), leadCase.getDisease(), leadCase.getDiseaseDetails(), leadCase.getDiseaseVariant());
            newContact.setPerson(new PersonReferenceDto(contact.getPerson().getUuid()));
            DtoHelper.copyDtoValues(newContact, contactFacade.toDto(contact), cloning);
            contactFacade.save(newContact, false, false);
        } else {
            // simply move existing entities to the merge target
            contact.setCaze(leadCase);
            contactService.ensurePersisted(contact);
        }
    }
    // 2.2 Samples
    List<Sample> samples = sampleService.findBy(new SampleCriteria().caze(otherCase.toReference()), null);
    for (Sample sample : samples) {
        if (cloning) {
            SampleDto newSample = SampleDto.build(sample.getReportingUser().toReference(), leadCase.toReference());
            DtoHelper.copyDtoValues(newSample, SampleFacadeEjb.toDto(sample), cloning);
            sampleFacade.saveSample(newSample, false, true, true);
            // 2.2.1 Pathogen Tests
            for (PathogenTest pathogenTest : sample.getPathogenTests()) {
                PathogenTestDto newPathogenTest = PathogenTestDto.build(newSample.toReference(), pathogenTest.getLabUser().toReference());
                DtoHelper.copyDtoValues(newPathogenTest, PathogenTestFacadeEjbLocal.toDto(pathogenTest), cloning);
                sampleTestFacade.savePathogenTest(newPathogenTest);
            }
            for (AdditionalTest additionalTest : sample.getAdditionalTests()) {
                AdditionalTestDto newAdditionalTest = AdditionalTestDto.build(newSample.toReference());
                DtoHelper.copyDtoValues(newAdditionalTest, AdditionalTestFacadeEjbLocal.toDto(additionalTest), cloning);
                additionalTestFacade.saveAdditionalTest(newAdditionalTest);
            }
        } else {
            // simply move existing entities to the merge target
            sample.setAssociatedCase(leadCase);
            sampleService.ensurePersisted(sample);
        }
    }
    // 2.3 Tasks
    if (!cloning) {
        // simply move existing entities to the merge target
        List<Task> tasks = taskService.findBy(new TaskCriteria().caze(new CaseReferenceDto(otherCase.getUuid())), true);
        for (Task task : tasks) {
            task.setCaze(leadCase);
            taskService.ensurePersisted(task);
        }
    }
    // 3 Change Therapy Reference
    // 3.1 Treatments
    List<Treatment> treatments = treatmentService.findBy(new TreatmentCriteria().therapy(new TherapyReferenceDto(otherCase.getTherapy().getUuid())));
    TherapyReferenceDto leadCaseTherapyReference = new TherapyReferenceDto(leadCase.getTherapy().getUuid());
    for (Treatment treatment : treatments) {
        if (cloning) {
            TreatmentDto newTreatment = TreatmentDto.build(leadCaseTherapyReference);
            DtoHelper.copyDtoValues(newTreatment, TreatmentFacadeEjb.toDto(treatment), cloning);
            treatmentFacade.saveTreatment(newTreatment);
        } else {
            // simply move existing entities to the merge target
            treatment.setTherapy(leadCase.getTherapy());
            treatmentService.ensurePersisted(treatment);
        }
    }
    // 3.2 Prescriptions
    List<Prescription> prescriptions = prescriptionService.findBy(new PrescriptionCriteria().therapy(new TherapyReferenceDto(otherCase.getTherapy().getUuid())));
    for (Prescription prescription : prescriptions) {
        if (cloning) {
            PrescriptionDto newPrescription = PrescriptionDto.buildPrescription(leadCaseTherapyReference);
            DtoHelper.copyDtoValues(newPrescription, PrescriptionFacadeEjb.toDto(prescription), cloning);
            prescriptionFacade.savePrescription(newPrescription);
        } else {
            // simply move existing entities to the merge target
            prescription.setTherapy(leadCase.getTherapy());
            prescriptionService.ensurePersisted(prescription);
        }
    }
    // 4 Change Clinical Course Reference
    // 4.1 Clinical Visits
    List<ClinicalVisit> clinicalVisits = clinicalVisitService.findBy(new ClinicalVisitCriteria().clinicalCourse(new ClinicalCourseReferenceDto(otherCase.getClinicalCourse().getUuid())));
    for (ClinicalVisit clinicalVisit : clinicalVisits) {
        if (cloning) {
            ClinicalVisitDto newClinicalVisit = ClinicalVisitDto.build(leadCaseData.getClinicalCourse().toReference(), leadCase.getDisease());
            DtoHelper.copyDtoValues(newClinicalVisit, ClinicalVisitFacadeEjb.toDto(clinicalVisit), cloning);
            clinicalVisitFacade.saveClinicalVisit(newClinicalVisit, leadCase.getUuid(), false);
        } else {
            // simply move existing entities to the merge target
            clinicalVisit.setClinicalCourse(leadCase.getClinicalCourse());
            clinicalVisitService.ensurePersisted(clinicalVisit);
        }
    }
    // (set the person and the disease of the visit, saveVisit does the rest)
    for (VisitDto otherVisit : otherCase.getVisits().stream().map(VisitFacadeEjb::toDto).collect(Collectors.toList())) {
        otherVisit.setPerson(leadCaseData.getPerson());
        otherVisit.setDisease(leadCaseData.getDisease());
        visitFacade.saveVisit(otherVisit);
    }
    // 6 Documents
    List<Document> documents = documentService.getRelatedToEntity(DocumentRelatedEntityType.CASE, otherCase.getUuid());
    for (Document document : documents) {
        document.setRelatedEntityUuid(leadCaseData.getUuid());
        documentService.ensurePersisted(document);
    }
    // 7 Persist Event links through eventparticipants
    Set<EventParticipant> eventParticipants = otherCase.getEventParticipants();
    for (EventParticipant eventParticipant : eventParticipants) {
        eventParticipant.setResultingCase(leadCase);
        eventParticipantService.ensurePersisted(eventParticipant);
    }
    otherCase.getEventParticipants().clear();
    // 8 Exposures - Make sure there are no two probable infection environments
    // if there are more than 2 exposures marked as probable infection environment, find the one that originates from the otherCase and set it to false
    // the one originating from the otherCase should always be found at the higher index
    List<Exposure> probableExposuresList = leadCase.getEpiData().getExposures().stream().filter(Exposure::isProbableInfectionEnvironment).collect(Collectors.toList());
    while (probableExposuresList.size() >= 2) {
        // should never be > 2, but still make sure to set all but one exposures to false
        probableExposuresList.get(probableExposuresList.size() - 1).setProbableInfectionEnvironment(false);
        exposureService.ensurePersisted(probableExposuresList.get(probableExposuresList.size() - 1));
        probableExposuresList.remove(probableExposuresList.size() - 1);
    }
    // 9 Reports
    List<SurveillanceReport> surveillanceReports = surveillanceReportService.getByCaseUuids(Collections.singletonList(otherCase.getUuid()));
    surveillanceReports.forEach(surveillanceReport -> {
        SurveillanceReportDto surveillanceReportDto = SurveillanceReportFacadeEjb.toDto(surveillanceReport);
        surveillanceReportDto.setCaze(leadCase.toReference());
        surveillanceReportFacade.saveSurveillanceReport(surveillanceReportDto);
    });
    // 10 Activity as case
    final EpiData otherEpiData = otherCase.getEpiData();
    if (otherEpiData != null && YesNoUnknown.YES == otherEpiData.getActivityAsCaseDetailsKnown() && CollectionUtils.isNotEmpty(otherEpiData.getActivitiesAsCase())) {
        final EpiData leadEpiData = leadCase.getEpiData();
        leadEpiData.setActivityAsCaseDetailsKnown(YesNoUnknown.YES);
        epiDataService.ensurePersisted(leadEpiData);
    }
    // Travel entries reference
    List<TravelEntry> travelEntries = travelEntryService.getAllByResultingCase(otherCase);
    travelEntries.forEach(t -> {
        t.setResultingCase(leadCase);
        travelEntryService.ensurePersisted(t);
    });
}
Also used : AdditionalTest(de.symeda.sormas.backend.sample.AdditionalTest) Prescription(de.symeda.sormas.backend.therapy.Prescription) TravelEntry(de.symeda.sormas.backend.travelentry.TravelEntry) PrescriptionCriteria(de.symeda.sormas.api.therapy.PrescriptionCriteria) Task(de.symeda.sormas.backend.task.Task) SurveillanceReport(de.symeda.sormas.backend.caze.surveillancereport.SurveillanceReport) PersonReferenceDto(de.symeda.sormas.api.person.PersonReferenceDto) ClinicalVisitCriteria(de.symeda.sormas.api.clinicalcourse.ClinicalVisitCriteria) PathogenTestDto(de.symeda.sormas.api.sample.PathogenTestDto) Document(de.symeda.sormas.backend.document.Document) TreatmentDto(de.symeda.sormas.api.therapy.TreatmentDto) ContactCriteria(de.symeda.sormas.api.contact.ContactCriteria) ContactDto(de.symeda.sormas.api.contact.ContactDto) PrescriptionDto(de.symeda.sormas.api.therapy.PrescriptionDto) TreatmentCriteria(de.symeda.sormas.api.therapy.TreatmentCriteria) TaskCriteria(de.symeda.sormas.api.task.TaskCriteria) EpiData(de.symeda.sormas.backend.epidata.EpiData) ClinicalCourseReferenceDto(de.symeda.sormas.api.clinicalcourse.ClinicalCourseReferenceDto) PersonDto(de.symeda.sormas.api.person.PersonDto) CasePersonDto(de.symeda.sormas.api.caze.CasePersonDto) Sample(de.symeda.sormas.backend.sample.Sample) SampleCriteria(de.symeda.sormas.api.sample.SampleCriteria) TherapyReferenceDto(de.symeda.sormas.api.therapy.TherapyReferenceDto) Exposure(de.symeda.sormas.backend.exposure.Exposure) PathogenTest(de.symeda.sormas.backend.sample.PathogenTest) ClinicalVisit(de.symeda.sormas.backend.clinicalcourse.ClinicalVisit) Contact(de.symeda.sormas.backend.contact.Contact) Treatment(de.symeda.sormas.backend.therapy.Treatment) ClinicalVisitDto(de.symeda.sormas.api.clinicalcourse.ClinicalVisitDto) VisitDto(de.symeda.sormas.api.visit.VisitDto) ClinicalVisitDto(de.symeda.sormas.api.clinicalcourse.ClinicalVisitDto) SurveillanceReportDto(de.symeda.sormas.api.caze.surveillancereport.SurveillanceReportDto) SampleDto(de.symeda.sormas.api.sample.SampleDto) CaseReferenceDto(de.symeda.sormas.api.caze.CaseReferenceDto) EventParticipant(de.symeda.sormas.backend.event.EventParticipant) AdditionalTestDto(de.symeda.sormas.api.sample.AdditionalTestDto)

Example 2 with Treatment

use of de.symeda.sormas.backend.therapy.Treatment in project SORMAS-Project by hzi-braunschweig.

the class CaseService method createCriteriaFilter.

public <T extends AbstractDomainObject> Predicate createCriteriaFilter(CaseCriteria caseCriteria, CaseQueryContext caseQueryContext) {
    final From<?, Case> from = caseQueryContext.getRoot();
    final CriteriaBuilder cb = caseQueryContext.getCriteriaBuilder();
    final CriteriaQuery<?> cq = caseQueryContext.getQuery();
    final CaseJoins<Case> joins = (CaseJoins<Case>) caseQueryContext.getJoins();
    Join<Case, Person> person = joins.getPerson();
    Join<Case, User> reportingUser = joins.getReportingUser();
    Join<Case, Facility> facility = joins.getFacility();
    Join<Person, Location> location = person.join(Person.ADDRESS, JoinType.LEFT);
    Predicate filter = null;
    if (caseCriteria.getReportingUserRole() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.isMember(caseCriteria.getReportingUserRole(), from.join(Case.REPORTING_USER, JoinType.LEFT).get(User.USER_ROLES)));
    }
    if (caseCriteria.getDisease() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.DISEASE), caseCriteria.getDisease()));
    }
    if (caseCriteria.getDiseaseVariant() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.DISEASE_VARIANT), caseCriteria.getDiseaseVariant()));
    }
    if (caseCriteria.getOutcome() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.OUTCOME), caseCriteria.getOutcome()));
    }
    if (caseCriteria.getRegion() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, CaseCriteriaHelper.createRegionFilterWithFallback(cb, joins, caseCriteria.getRegion()));
    }
    if (caseCriteria.getDistrict() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, CaseCriteriaHelper.createDistrictFilterWithFallback(cb, joins, caseCriteria.getDistrict()));
    }
    if (caseCriteria.getCommunity() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, CaseCriteriaHelper.createCommunityFilterWithFallback(cb, joins, caseCriteria.getCommunity()));
    }
    if (caseCriteria.getFollowUpStatus() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.FOLLOW_UP_STATUS), caseCriteria.getFollowUpStatus()));
    }
    if (caseCriteria.getFollowUpUntilFrom() != null && caseCriteria.getFollowUpUntilTo() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.between(from.get(Case.FOLLOW_UP_UNTIL), caseCriteria.getFollowUpUntilFrom(), caseCriteria.getFollowUpUntilTo()));
    } else if (caseCriteria.getFollowUpUntilFrom() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.greaterThanOrEqualTo(from.get(Case.FOLLOW_UP_UNTIL), caseCriteria.getFollowUpUntilFrom()));
    } else if (caseCriteria.getFollowUpUntilTo() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.lessThanOrEqualTo(from.get(Case.FOLLOW_UP_UNTIL), caseCriteria.getFollowUpUntilTo()));
    }
    if (caseCriteria.getSymptomJournalStatus() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(person.get(Person.SYMPTOM_JOURNAL_STATUS), caseCriteria.getSymptomJournalStatus()));
    }
    if (caseCriteria.getVaccinationStatus() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.VACCINATION_STATUS), caseCriteria.getVaccinationStatus()));
    }
    if (caseCriteria.getReinfectionStatus() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.REINFECTION_STATUS), caseCriteria.getReinfectionStatus()));
    }
    if (caseCriteria.getReportDateTo() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.lessThanOrEqualTo(from.get(Case.REPORT_DATE), caseCriteria.getReportDateTo()));
    }
    if (caseCriteria.getCaseOrigin() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.CASE_ORIGIN), caseCriteria.getCaseOrigin()));
    }
    if (caseCriteria.getHealthFacility() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.join(Case.HEALTH_FACILITY, JoinType.LEFT).get(Facility.UUID), caseCriteria.getHealthFacility().getUuid()));
    }
    if (caseCriteria.getFacilityTypeGroup() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, from.get(Case.FACILITY_TYPE).in(FacilityType.getTypes(caseCriteria.getFacilityTypeGroup())));
    }
    if (caseCriteria.getFacilityType() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.FACILITY_TYPE), caseCriteria.getFacilityType()));
    }
    if (caseCriteria.getPointOfEntry() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.join(Case.POINT_OF_ENTRY, JoinType.LEFT).get(PointOfEntry.UUID), caseCriteria.getPointOfEntry().getUuid()));
    }
    if (caseCriteria.getSurveillanceOfficer() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.join(Case.SURVEILLANCE_OFFICER, JoinType.LEFT).get(User.UUID), caseCriteria.getSurveillanceOfficer().getUuid()));
    }
    if (caseCriteria.getCaseClassification() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.CASE_CLASSIFICATION), caseCriteria.getCaseClassification()));
    }
    if (caseCriteria.getInvestigationStatus() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.INVESTIGATION_STATUS), caseCriteria.getInvestigationStatus()));
    }
    if (caseCriteria.getPresentCondition() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(person.get(Person.PRESENT_CONDITION), caseCriteria.getPresentCondition()));
    }
    if (caseCriteria.getNewCaseDateFrom() != null && caseCriteria.getNewCaseDateTo() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, createNewCaseFilter(cq, cb, from, DateHelper.getStartOfDay(caseCriteria.getNewCaseDateFrom()), DateHelper.getEndOfDay(caseCriteria.getNewCaseDateTo()), caseCriteria.getNewCaseDateType()));
    }
    if (caseCriteria.getCreationDateFrom() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.greaterThan(from.get(Case.CREATION_DATE), DateHelper.getStartOfDay(caseCriteria.getCreationDateFrom())));
    }
    if (caseCriteria.getCreationDateTo() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.lessThan(from.get(Case.CREATION_DATE), DateHelper.getEndOfDay(caseCriteria.getCreationDateTo())));
    }
    if (caseCriteria.getQuarantineType() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.QUARANTINE), caseCriteria.getQuarantineType()));
    }
    if (caseCriteria.getQuarantineTo() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.between(from.get(Case.QUARANTINE_TO), DateHelper.getStartOfDay(caseCriteria.getQuarantineTo()), DateHelper.getEndOfDay(caseCriteria.getQuarantineTo())));
    }
    if (caseCriteria.getPerson() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(person.get(Person.UUID), caseCriteria.getPerson().getUuid()));
    }
    if (caseCriteria.getMustHaveNoGeoCoordinates() != null && caseCriteria.getMustHaveNoGeoCoordinates() == true) {
        Join<Person, Location> personAddress = person.join(Person.ADDRESS, JoinType.LEFT);
        filter = CriteriaBuilderHelper.and(cb, filter, cb.and(cb.or(cb.isNull(from.get(Case.REPORT_LAT)), cb.isNull(from.get(Case.REPORT_LON))), cb.or(cb.isNull(personAddress.get(Location.LATITUDE)), cb.isNull(personAddress.get(Location.LONGITUDE)))));
    }
    if (caseCriteria.getMustBePortHealthCaseWithoutFacility() != null && caseCriteria.getMustBePortHealthCaseWithoutFacility() == true) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.and(cb.equal(from.get(Case.CASE_ORIGIN), CaseOrigin.POINT_OF_ENTRY), cb.isNull(from.join(Case.HEALTH_FACILITY, JoinType.LEFT))));
    }
    if (caseCriteria.getMustHaveCaseManagementData() != null && caseCriteria.getMustHaveCaseManagementData() == true) {
        Subquery<Prescription> prescriptionSubquery = cq.subquery(Prescription.class);
        Root<Prescription> prescriptionRoot = prescriptionSubquery.from(Prescription.class);
        prescriptionSubquery.select(prescriptionRoot).where(cb.equal(prescriptionRoot.get(Prescription.THERAPY), from.get(Case.THERAPY)));
        Subquery<Treatment> treatmentSubquery = cq.subquery(Treatment.class);
        Root<Treatment> treatmentRoot = treatmentSubquery.from(Treatment.class);
        treatmentSubquery.select(treatmentRoot).where(cb.equal(treatmentRoot.get(Treatment.THERAPY), from.get(Case.THERAPY)));
        Subquery<ClinicalVisit> clinicalVisitSubquery = cq.subquery(ClinicalVisit.class);
        Root<ClinicalVisit> clinicalVisitRoot = clinicalVisitSubquery.from(ClinicalVisit.class);
        clinicalVisitSubquery.select(clinicalVisitRoot).where(cb.equal(clinicalVisitRoot.get(ClinicalVisit.CLINICAL_COURSE), from.get(Case.CLINICAL_COURSE)));
        filter = CriteriaBuilderHelper.and(cb, filter, cb.or(cb.exists(prescriptionSubquery), cb.exists(treatmentSubquery), cb.exists(clinicalVisitSubquery)));
    }
    if (Boolean.TRUE.equals(caseCriteria.getWithoutResponsibleOfficer())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.isNull(from.get(Case.SURVEILLANCE_OFFICER)));
    }
    if (Boolean.TRUE.equals(caseCriteria.getWithExtendedQuarantine())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.isTrue(from.get(Case.QUARANTINE_EXTENDED)));
    }
    if (Boolean.TRUE.equals(caseCriteria.getWithReducedQuarantine())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.isTrue(from.get(Case.QUARANTINE_REDUCED)));
    }
    if (Boolean.TRUE.equals(caseCriteria.getOnlyQuarantineHelpNeeded())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.and(cb.notEqual(from.get(Case.QUARANTINE_HELP_NEEDED), ""), cb.isNotNull(from.get(Case.QUARANTINE_HELP_NEEDED))));
    }
    if (caseCriteria.getRelevanceStatus() != null) {
        if (caseCriteria.getRelevanceStatus() == EntityRelevanceStatus.ACTIVE) {
            filter = CriteriaBuilderHelper.and(cb, filter, cb.or(cb.equal(from.get(Case.ARCHIVED), false), cb.isNull(from.get(Case.ARCHIVED))));
        } else if (caseCriteria.getRelevanceStatus() == EntityRelevanceStatus.ARCHIVED) {
            filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.ARCHIVED), true));
        }
    }
    if (caseCriteria.getDeleted() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.DELETED), caseCriteria.getDeleted()));
    }
    if (!DataHelper.isNullOrEmpty(caseCriteria.getPersonLike())) {
        Predicate likeFilters = CriteriaBuilderHelper.buildFreeTextSearchPredicate(cb, caseCriteria.getPersonLike(), textFilter -> cb.or(// We should allow short and long versions of the UUID so let's do a LIKE behaving like a "starts with"
        CriteriaBuilderHelper.ilikePrecise(cb, person.get(Person.UUID), textFilter + "%"), CriteriaBuilderHelper.unaccentedIlike(cb, person.get(Person.FIRST_NAME), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, person.get(Person.LAST_NAME), textFilter), phoneNumberPredicate(cb, (Expression<String>) caseQueryContext.getSubqueryExpression(ContactQueryContext.PERSON_PHONE_SUBQUERY), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, location.get(Location.CITY), textFilter), CriteriaBuilderHelper.ilike(cb, location.get(Location.POSTAL_CODE), textFilter)));
        filter = CriteriaBuilderHelper.and(cb, filter, likeFilters);
    }
    if (!DataHelper.isNullOrEmpty(caseCriteria.getCaseLike())) {
        Predicate likeFilters = CriteriaBuilderHelper.buildFreeTextSearchPredicate(cb, caseCriteria.getCaseLike(), textFilter -> cb.or(CriteriaBuilderHelper.ilike(cb, from.get(Case.UUID), textFilter), CriteriaBuilderHelper.ilike(cb, from.get(Case.EPID_NUMBER), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, facility.get(Facility.NAME), textFilter), CriteriaBuilderHelper.ilike(cb, from.get(Case.EXTERNAL_ID), textFilter), CriteriaBuilderHelper.ilike(cb, from.get(Case.EXTERNAL_TOKEN), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, from.get(Case.HEALTH_FACILITY_DETAILS), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, from.get(Case.INTERNAL_TOKEN), textFilter)));
        filter = CriteriaBuilderHelper.and(cb, filter, likeFilters);
    }
    boolean hasEventLikeCriteria = caseCriteria.getEventLike() != null && !caseCriteria.getEventLike().trim().isEmpty();
    boolean hasOnlyCasesWithEventsCriteria = Boolean.TRUE.equals(caseCriteria.getOnlyCasesWithEvents());
    if (hasEventLikeCriteria || hasOnlyCasesWithEventsCriteria) {
        Join<Case, EventParticipant> eventParticipant = joins.getEventParticipants();
        Join<EventParticipant, Event> event = eventParticipant.join(EventParticipant.EVENT, JoinType.LEFT);
        filter = CriteriaBuilderHelper.and(cb, filter, cb.isFalse(event.get(Event.DELETED)), cb.isFalse(event.get(Event.ARCHIVED)), cb.isFalse(eventParticipant.get(EventParticipant.DELETED)));
        if (hasEventLikeCriteria) {
            String[] textFilters = caseCriteria.getEventLike().trim().split("\\s+");
            for (String textFilter : textFilters) {
                Predicate likeFilters = cb.or(CriteriaBuilderHelper.unaccentedIlike(cb, event.get(Event.EVENT_DESC), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, event.get(Event.EVENT_TITLE), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, event.get(Event.INTERNAL_TOKEN), textFilter), CriteriaBuilderHelper.ilike(cb, event.get(Event.UUID), textFilter));
                filter = CriteriaBuilderHelper.and(cb, filter, likeFilters, cb.isFalse(eventParticipant.get(EventParticipant.DELETED)));
            }
        }
        if (hasOnlyCasesWithEventsCriteria) {
            filter = CriteriaBuilderHelper.and(cb, filter, cb.isNotNull(event.get(Event.ID)));
        }
    }
    if (caseCriteria.getReportingUserLike() != null) {
        String[] textFilters = caseCriteria.getReportingUserLike().split("\\s+");
        for (String textFilter : textFilters) {
            Predicate likeFilters = cb.or(CriteriaBuilderHelper.unaccentedIlike(cb, reportingUser.get(User.FIRST_NAME), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, reportingUser.get(User.LAST_NAME), textFilter), CriteriaBuilderHelper.unaccentedIlike(cb, reportingUser.get(User.USER_NAME), textFilter));
            filter = CriteriaBuilderHelper.and(cb, filter, likeFilters);
        }
    }
    if (caseCriteria.getBirthdateYYYY() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(person.get(Person.BIRTHDATE_YYYY), caseCriteria.getBirthdateYYYY()));
    }
    if (caseCriteria.getBirthdateMM() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(person.get(Person.BIRTHDATE_MM), caseCriteria.getBirthdateMM()));
    }
    if (caseCriteria.getBirthdateDD() != null) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(person.get(Person.BIRTHDATE_DD), caseCriteria.getBirthdateDD()));
    }
    if (Boolean.TRUE.equals(caseCriteria.getOnlyContactsFromOtherInstances())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.or(cb.isNotNull(joins.getSormasToSormasShareInfo().get(SormasToSormasShareInfo.CAZE)), cb.isNotNull(from.get(Case.SORMAS_TO_SORMAS_ORIGIN_INFO))));
    }
    if (Boolean.TRUE.equals(caseCriteria.getOnlyCasesWithReinfection())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.RE_INFECTION), YesNoUnknown.YES));
    }
    if (Boolean.TRUE.equals(caseCriteria.getOnlyCasesWithDontShareWithExternalSurvTool())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.isTrue(from.get(Case.DONT_SHARE_WITH_REPORTING_TOOL)));
    }
    if (Boolean.TRUE.equals(caseCriteria.getOnlyShowCasesWithFulfilledReferenceDefinition())) {
        filter = CriteriaBuilderHelper.and(cb, filter, cb.equal(from.get(Case.CASE_REFERENCE_DEFINITION), CaseReferenceDefinition.FULFILLED));
    }
    filter = CriteriaBuilderHelper.and(cb, filter, externalShareInfoService.buildShareCriteriaFilter(caseCriteria, cq, cb, from, ExternalShareInfo.CAZE, (latestShareDate) -> createChangeDateFilter(cb, from, latestShareDate, false)));
    return filter;
}
Also used : Prescription(de.symeda.sormas.backend.therapy.Prescription) User(de.symeda.sormas.backend.user.User) Predicate(javax.persistence.criteria.Predicate) CaseJoins(de.symeda.sormas.utils.CaseJoins) CriteriaBuilder(javax.persistence.criteria.CriteriaBuilder) ClinicalVisit(de.symeda.sormas.backend.clinicalcourse.ClinicalVisit) Treatment(de.symeda.sormas.backend.therapy.Treatment) Event(de.symeda.sormas.backend.event.Event) Facility(de.symeda.sormas.backend.infrastructure.facility.Facility) Person(de.symeda.sormas.backend.person.Person) EventParticipant(de.symeda.sormas.backend.event.EventParticipant) Location(de.symeda.sormas.backend.location.Location)

Aggregations

ClinicalVisit (de.symeda.sormas.backend.clinicalcourse.ClinicalVisit)2 EventParticipant (de.symeda.sormas.backend.event.EventParticipant)2 Prescription (de.symeda.sormas.backend.therapy.Prescription)2 Treatment (de.symeda.sormas.backend.therapy.Treatment)2 CasePersonDto (de.symeda.sormas.api.caze.CasePersonDto)1 CaseReferenceDto (de.symeda.sormas.api.caze.CaseReferenceDto)1 SurveillanceReportDto (de.symeda.sormas.api.caze.surveillancereport.SurveillanceReportDto)1 ClinicalCourseReferenceDto (de.symeda.sormas.api.clinicalcourse.ClinicalCourseReferenceDto)1 ClinicalVisitCriteria (de.symeda.sormas.api.clinicalcourse.ClinicalVisitCriteria)1 ClinicalVisitDto (de.symeda.sormas.api.clinicalcourse.ClinicalVisitDto)1 ContactCriteria (de.symeda.sormas.api.contact.ContactCriteria)1 ContactDto (de.symeda.sormas.api.contact.ContactDto)1 PersonDto (de.symeda.sormas.api.person.PersonDto)1 PersonReferenceDto (de.symeda.sormas.api.person.PersonReferenceDto)1 AdditionalTestDto (de.symeda.sormas.api.sample.AdditionalTestDto)1 PathogenTestDto (de.symeda.sormas.api.sample.PathogenTestDto)1 SampleCriteria (de.symeda.sormas.api.sample.SampleCriteria)1 SampleDto (de.symeda.sormas.api.sample.SampleDto)1 TaskCriteria (de.symeda.sormas.api.task.TaskCriteria)1 PrescriptionCriteria (de.symeda.sormas.api.therapy.PrescriptionCriteria)1