From 4530278f7b7a9c2b23c1d005b826d6b638929c61 Mon Sep 17 00:00:00 2001 From: zubaira Date: Thu, 28 Nov 2024 11:32:12 +0100 Subject: [PATCH] Fix: Prioritize payload/bundled events over database events for enrollment[DHIS2-17806] --- .../DefaultProgramRuleService.java | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/programrule/DefaultProgramRuleService.java b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/programrule/DefaultProgramRuleService.java index d401ae7013ae..db6c6183212d 100644 --- a/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/programrule/DefaultProgramRuleService.java +++ b/dhis-2/dhis-services/dhis-service-tracker/src/main/java/org/hisp/dhis/tracker/programrule/DefaultProgramRuleService.java @@ -34,7 +34,6 @@ import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import java.util.stream.Stream; import lombok.RequiredArgsConstructor; import org.apache.commons.collections4.ListUtils; import org.hisp.dhis.dxf2.events.event.EventQueryParams; @@ -207,19 +206,34 @@ private List getAttributes( // if they are present in both places private Set getEventsFromEnrollment( String enrollmentUid, TrackerBundle bundle, TrackerPreheat preheat) { + + // Fetch events linked to the enrollment from the database EventQueryParams eventQueryParams = new EventQueryParams(); eventQueryParams.setProgramInstances(Set.of(enrollmentUid)); - List events = + List dbEvents = eventService.getEvents(eventQueryParams).getEvents(); - Stream programStageInstances = - events.stream().map(e -> programStageInstanceService.getProgramStageInstance(e.getUid())); + // Convert DB events to ProgramStageInstances + Map dbProgramStageInstances = + dbEvents.stream() + .collect( + Collectors.toMap( + org.hisp.dhis.dxf2.events.event.Event::getUid, + e -> programStageInstanceService.getProgramStageInstance(e.getUid()))); - Stream bundleEvents = + // Fetch events from the payload for the given enrollment + Map payloadProgramStageInstances = bundle.getEvents().stream() - .filter(e -> e.getEnrollment().equals(enrollmentUid)) - .map(event -> eventTrackerConverterService.fromForRuleEngine(preheat, event)); + .filter(event -> event.getEnrollment().equals(enrollmentUid)) + .collect( + Collectors.toMap( + Event::getUid, + event -> eventTrackerConverterService.fromForRuleEngine(preheat, event))); + + // Merge payload events (prioritized) with DB events + dbProgramStageInstances.putAll(payloadProgramStageInstances); - return Stream.concat(programStageInstances, bundleEvents).collect(Collectors.toSet()); + // Return a Set of unique ProgramStageInstances + return new HashSet<>(dbProgramStageInstances.values()); } }