Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Move converters into the bundle package [DHIS2-18093] #18807

Merged
merged 3 commits into from
Oct 15, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,348 @@
/*
* Copyright (c) 2004-2024, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.tracker.imports.bundle;

import static org.apache.commons.collections4.CollectionUtils.isNotEmpty;
import static org.hisp.dhis.program.EnrollmentStatus.COMPLETED;
import static org.hisp.dhis.relationship.RelationshipEntity.PROGRAM_INSTANCE;
import static org.hisp.dhis.relationship.RelationshipEntity.PROGRAM_STAGE_INSTANCE;
import static org.hisp.dhis.relationship.RelationshipEntity.TRACKED_ENTITY_INSTANCE;

import java.util.Date;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.hisp.dhis.category.CategoryOptionCombo;
import org.hisp.dhis.dataelement.DataElement;
import org.hisp.dhis.event.EventStatus;
import org.hisp.dhis.eventdatavalue.EventDataValue;
import org.hisp.dhis.note.Note;
import org.hisp.dhis.organisationunit.OrganisationUnit;
import org.hisp.dhis.program.Enrollment;
import org.hisp.dhis.program.EnrollmentStatus;
import org.hisp.dhis.program.Event;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramStage;
import org.hisp.dhis.program.UserInfoSnapshot;
import org.hisp.dhis.relationship.Relationship;
import org.hisp.dhis.relationship.RelationshipItem;
import org.hisp.dhis.relationship.RelationshipKey;
import org.hisp.dhis.relationship.RelationshipType;
import org.hisp.dhis.trackedentity.TrackedEntity;
import org.hisp.dhis.trackedentity.TrackedEntityType;
import org.hisp.dhis.tracker.imports.domain.DataValue;
import org.hisp.dhis.tracker.imports.preheat.TrackerPreheat;
import org.hisp.dhis.tracker.imports.util.RelationshipKeySupport;
import org.hisp.dhis.user.User;
import org.hisp.dhis.user.UserDetails;
import org.hisp.dhis.util.DateUtils;

/**
* TrackerObjectsMapper maps tracker domain objects to Hibernate Objects so they can be persisted in
enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
* the DB. This class provides static methods to convert imported domain objects such as {@link
* TrackedEntity}, {@link Enrollment}, {@link Event}, and {@link Relationship} into their
* corresponding database entities. It gets existing records from the database throw the preheat and
enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
* maps the incoming data accordingly, ensuring that all necessary fields are populated correctly.
* All the values that should be set by the system are set here (eg. createdAt, updatedBy...)
*/
public class TrackerObjectsMapper {
private TrackerObjectsMapper() {
throw new IllegalStateException("Utility class");
}

public static @Nonnull TrackedEntity map(
@Nonnull TrackerPreheat preheat,
@Nonnull org.hisp.dhis.tracker.imports.domain.TrackedEntity trackedEntity,
@Nonnull UserDetails user) {
TrackedEntity dbTrackedEntity = preheat.getTrackedEntity(trackedEntity.getTrackedEntity());
OrganisationUnit organisationUnit = preheat.getOrganisationUnit(trackedEntity.getOrgUnit());
TrackedEntityType trackedEntityType =
preheat.getTrackedEntityType(trackedEntity.getTrackedEntityType());

Date now = new Date();

if (dbTrackedEntity == null) {
dbTrackedEntity = new TrackedEntity();
dbTrackedEntity.setUid(trackedEntity.getTrackedEntity());
dbTrackedEntity.setCreated(now);
dbTrackedEntity.setCreatedByUserInfo(UserInfoSnapshot.from(user));
dbTrackedEntity.setStoredBy(trackedEntity.getStoredBy());
}

dbTrackedEntity.setLastUpdatedByUserInfo(UserInfoSnapshot.from(user));
enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
dbTrackedEntity.setLastUpdated(now);
dbTrackedEntity.setPotentialDuplicate(trackedEntity.isPotentialDuplicate());
dbTrackedEntity.setCreatedAtClient(DateUtils.fromInstant(trackedEntity.getCreatedAtClient()));
dbTrackedEntity.setLastUpdatedAtClient(
DateUtils.fromInstant(trackedEntity.getUpdatedAtClient()));
dbTrackedEntity.setOrganisationUnit(organisationUnit);
dbTrackedEntity.setTrackedEntityType(trackedEntityType);
dbTrackedEntity.setInactive(trackedEntity.isInactive());
dbTrackedEntity.setGeometry(trackedEntity.getGeometry());

return dbTrackedEntity;
}

public static @Nonnull Enrollment map(
@Nonnull TrackerPreheat preheat,
@Nonnull org.hisp.dhis.tracker.imports.domain.Enrollment enrollment,
@Nonnull UserDetails user) {
Enrollment dbEnrollment = preheat.getEnrollment(enrollment.getEnrollment());
OrganisationUnit organisationUnit = preheat.getOrganisationUnit(enrollment.getOrgUnit());

Program program = preheat.getProgram(enrollment.getProgram());

TrackedEntity trackedEntity = preheat.getTrackedEntity(enrollment.getTrackedEntity());

Date now = new Date();

if (dbEnrollment == null) {
dbEnrollment = new Enrollment();
dbEnrollment.setUid(enrollment.getEnrollment());
dbEnrollment.setCreated(now);
dbEnrollment.setStoredBy(enrollment.getStoredBy());
dbEnrollment.setCreatedByUserInfo(UserInfoSnapshot.from(user));
}

dbEnrollment.setLastUpdated(now);
dbEnrollment.setLastUpdatedByUserInfo(UserInfoSnapshot.from(user));
dbEnrollment.setCreatedAtClient(DateUtils.fromInstant(enrollment.getCreatedAtClient()));
dbEnrollment.setLastUpdatedAtClient(DateUtils.fromInstant(enrollment.getUpdatedAtClient()));

Date enrollmentDate = DateUtils.fromInstant(enrollment.getEnrolledAt());
Date occurredDate = DateUtils.fromInstant(enrollment.getOccurredAt());

enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
dbEnrollment.setEnrollmentDate(enrollmentDate);
dbEnrollment.setOccurredDate(occurredDate != null ? occurredDate : enrollmentDate);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the difference between this one and enrollmentDate? and why do we set it to enrollmentDate if occurredDate is null?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Now the there is less code and it is easier to understand this logic I created https://dhis2.atlassian.net/browse/DHIS2-18224 to reason about this kind of stuff.
I am not sure what is the logic here

dbEnrollment.setOrganisationUnit(organisationUnit);
dbEnrollment.setProgram(program);
dbEnrollment.setTrackedEntity(trackedEntity);
dbEnrollment.setFollowup(enrollment.isFollowUp());
dbEnrollment.setGeometry(enrollment.getGeometry());

EnrollmentStatus previousStatus = dbEnrollment.getStatus();
dbEnrollment.setStatus(enrollment.getStatus());

if (previousStatus != dbEnrollment.getStatus()) {
enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
switch (dbEnrollment.getStatus()) {
case ACTIVE -> {
dbEnrollment.setCompletedDate(null);
dbEnrollment.setCompletedBy(null);
}
case COMPLETED -> {
dbEnrollment.setCompletedDate(now);
dbEnrollment.setCompletedBy(user.getUsername());
}
case CANCELLED -> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

unrelated to this PR, but I've seen that when the enrollment is CANCELLED, the related event(s) are not modified, so it could happen that an event is ACTIVE while the parent enrollment is CANCELLED, does that make sense?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as before, I just didn't change the logic, but in https://dhis2.atlassian.net/browse/DHIS2-18224 we should try to understand if it makes sense or not.

dbEnrollment.setCompletedDate(now);
dbEnrollment.setCompletedBy(null);
}
}
}

if (isNotEmpty(enrollment.getNotes())) {
dbEnrollment
.getNotes()
.addAll(
enrollment.getNotes().stream()
.map(note -> map(preheat, note, user))
.collect(Collectors.toSet()));
}
return dbEnrollment;
}

public static @Nonnull Event map(
@Nonnull TrackerPreheat preheat,
@Nonnull org.hisp.dhis.tracker.imports.domain.Event event,
@Nonnull UserDetails user) {
Event dbEvent = preheat.getEvent(event.getEvent());
ProgramStage programStage = preheat.getProgramStage(event.getProgramStage());
Program program = preheat.getProgram(event.getProgram());
OrganisationUnit organisationUnit = preheat.getOrganisationUnit(event.getOrgUnit());

Date now = new Date();

if (dbEvent == null) {
dbEvent = new Event();
dbEvent.setUid(event.getEvent());
dbEvent.setCreated(now);
dbEvent.setStoredBy(event.getStoredBy());
dbEvent.setCreatedByUserInfo(UserInfoSnapshot.from(user));
}
dbEvent.setCreatedAtClient(DateUtils.fromInstant(event.getCreatedAtClient()));
dbEvent.setLastUpdatedByUserInfo(UserInfoSnapshot.from(user));
dbEvent.setLastUpdated(now);
dbEvent.setLastUpdatedAtClient(DateUtils.fromInstant(event.getUpdatedAtClient()));
dbEvent.setEnrollment(getEnrollment(preheat, event.getEnrollment(), program));
dbEvent.setProgramStage(programStage);
dbEvent.setOrganisationUnit(organisationUnit);
dbEvent.setOccurredDate(DateUtils.fromInstant(event.getOccurredAt()));
dbEvent.setScheduledDate(DateUtils.fromInstant(event.getScheduledAt()));

if (event.getAttributeOptionCombo().isNotBlank()) {
dbEvent.setAttributeOptionCombo(
preheat.getCategoryOptionCombo(event.getAttributeOptionCombo()));
} else {
dbEvent.setAttributeOptionCombo(preheat.getDefault(CategoryOptionCombo.class));
}

dbEvent.setGeometry(event.getGeometry());

EventStatus currentStatus = event.getStatus();
EventStatus previousStatus = dbEvent.getStatus();

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

like above if you make a paragraph (no empty lines) in between all the status logic its easier to read this logic

if (currentStatus != previousStatus && currentStatus == EventStatus.COMPLETED) {
dbEvent.setCompletedDate(now);
dbEvent.setCompletedBy(user.getUsername());
}

if (currentStatus != EventStatus.COMPLETED) {
dbEvent.setCompletedDate(null);
dbEvent.setCompletedBy(null);
}

dbEvent.setStatus(currentStatus);

if (Boolean.TRUE.equals(programStage.isEnableUserAssignment())
&& event.getAssignedUser() != null
&& !event.getAssignedUser().isEmpty()) {
Optional<User> assignedUser =
preheat.getUserByUsername(event.getAssignedUser().getUsername());
assignedUser.ifPresent(dbEvent::setAssignedUser);
}

if (program.isRegistration()
&& dbEvent.getScheduledDate() == null
&& dbEvent.getOccurredDate() != null) {
dbEvent.setScheduledDate(dbEvent.getOccurredDate());
}

// TODO(DHIS2-18223): Remove data value mapping and fix changelog logic
for (DataValue dataValue : event.getDataValues()) {
DataElement dataElement = preheat.getDataElement(dataValue.getDataElement());

EventDataValue eventDataValue = new EventDataValue();
eventDataValue.setDataElement(dataElement.getUid());
eventDataValue.setCreated(DateUtils.fromInstant(dataValue.getCreatedAt()));
eventDataValue.setCreatedByUserInfo(UserInfoSnapshot.from(user));
eventDataValue.setValue(dataValue.getValue());
eventDataValue.setLastUpdated(now);
eventDataValue.setProvidedElsewhere(dataValue.isProvidedElsewhere());
eventDataValue.setLastUpdatedByUserInfo(UserInfoSnapshot.from(user));

dbEvent.getEventDataValues().add(eventDataValue);
}

if (isNotEmpty(event.getNotes())) {
dbEvent
.getNotes()
.addAll(
event.getNotes().stream()
.map(note -> map(preheat, note, user))
.collect(Collectors.toSet()));
}

return dbEvent;
}

public static @Nonnull Relationship map(
@Nonnull TrackerPreheat preheat,
@Nonnull org.hisp.dhis.tracker.imports.domain.Relationship relationship,
@Nonnull UserDetails user) {
RelationshipType relationshipType =
preheat.getRelationshipType(relationship.getRelationshipType());
RelationshipItem fromItem = new org.hisp.dhis.relationship.RelationshipItem();
enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
RelationshipItem toItem = new org.hisp.dhis.relationship.RelationshipItem();

Date now = new Date();
Relationship dbRelationship = new org.hisp.dhis.relationship.Relationship();
dbRelationship.setUid(relationship.getRelationship());
dbRelationship.setCreated(now);
dbRelationship.setLastUpdated(now);
dbRelationship.setLastUpdatedBy(preheat.getUserByUid(user.getUid()).orElse(null));
dbRelationship.setRelationshipType(relationshipType);
dbRelationship.setCreatedAtClient(DateUtils.fromInstant(relationship.getCreatedAtClient()));

// FROM
fromItem.setRelationship(dbRelationship);

switch (relationshipType.getFromConstraint().getRelationshipEntity()) {
case TRACKED_ENTITY_INSTANCE ->
fromItem.setTrackedEntity(
preheat.getTrackedEntity(relationship.getFrom().getTrackedEntity()));
case PROGRAM_INSTANCE ->
fromItem.setEnrollment(preheat.getEnrollment(relationship.getFrom().getEnrollment()));
case PROGRAM_STAGE_INSTANCE ->
fromItem.setEvent(preheat.getEvent(relationship.getFrom().getEvent()));
}

// TO
toItem.setRelationship(dbRelationship);

switch (relationshipType.getToConstraint().getRelationshipEntity()) {
case TRACKED_ENTITY_INSTANCE ->
toItem.setTrackedEntity(
preheat.getTrackedEntity(relationship.getTo().getTrackedEntity()));
case PROGRAM_INSTANCE ->
toItem.setEnrollment(preheat.getEnrollment(relationship.getTo().getEnrollment()));
case PROGRAM_STAGE_INSTANCE ->
toItem.setEvent(preheat.getEvent(relationship.getTo().getEvent()));
}

dbRelationship.setFrom(fromItem);
dbRelationship.setTo(toItem);
RelationshipKey relationshipKey =
RelationshipKeySupport.getRelationshipKey(relationship, relationshipType);
dbRelationship.setKey(relationshipKey.asString());
dbRelationship.setInvertedKey(relationshipKey.inverseKey().asString());

return dbRelationship;
}

private static @Nonnull Note map(
@Nonnull TrackerPreheat preheat,
@Nonnull org.hisp.dhis.tracker.imports.domain.Note note,
@Nonnull UserDetails user) {
Note dbNote = new Note();
dbNote.setAutoFields();
enricocolasante marked this conversation as resolved.
Show resolved Hide resolved
dbNote.setUid(note.getNote());
dbNote.setNoteText(note.getValue());

dbNote.setLastUpdatedBy(preheat.getUserByUid(user.getUid()).orElse(null));
dbNote.setCreator(note.getStoredBy());
return dbNote;
}

private static Enrollment getEnrollment(
TrackerPreheat preheat, String enrollment, Program program) {
return switch (program.getProgramType()) {
case WITH_REGISTRATION -> preheat.getEnrollment(enrollment);
case WITHOUT_REGISTRATION -> preheat.getEnrollmentsWithoutRegistration(program.getUid());
};
}
}
Loading
Loading