Search in sources :

Example 26 with RelationshipItem

use of org.hisp.dhis.relationship.RelationshipItem in project dhis2-core by dhis2.

the class AbstractTrackedEntityInstanceService method handleRelationships.

private ImportSummaries handleRelationships(TrackedEntityInstance dtoEntityInstance, org.hisp.dhis.trackedentity.TrackedEntityInstance daoEntityInstance, ImportOptions importOptions) {
    ImportSummaries importSummaries = new ImportSummaries();
    List<Relationship> create = new ArrayList<>();
    List<Relationship> update = new ArrayList<>();
    List<String> relationshipUids = dtoEntityInstance.getRelationships().stream().map(Relationship::getRelationship).collect(Collectors.toList());
    List<Relationship> delete = daoEntityInstance.getRelationshipItems().stream().map(RelationshipItem::getRelationship).filter(relationship -> trackerAccessManager.canWrite(importOptions.getUser(), relationship).isEmpty()).filter(relationship -> isTeiPartOfRelationship(relationship, daoEntityInstance)).map(org.hisp.dhis.relationship.Relationship::getUid).filter((uid) -> !relationshipUids.contains(uid)).map(uid -> {
        Relationship relationship = new Relationship();
        relationship.setRelationship(uid);
        return relationship;
    }).collect(Collectors.toList());
    for (Relationship relationship : dtoEntityInstance.getRelationships()) {
        if (importOptions.getImportStrategy() == ImportStrategy.SYNC && dtoEntityInstance.isDeleted()) {
            delete.add(relationship);
        } else if (relationship.getRelationship() == null) {
            org.hisp.dhis.dxf2.events.trackedentity.RelationshipItem relationshipItem = new org.hisp.dhis.dxf2.events.trackedentity.RelationshipItem();
            if (!isTeiPartOfRelationship(relationship, daoEntityInstance)) {
                relationshipItem.setTrackedEntityInstance(dtoEntityInstance);
                relationship.setFrom(relationshipItem);
            }
            create.add(relationship);
        } else {
            if (isTeiPartOfRelationship(relationship, daoEntityInstance)) {
                if (_relationshipService.relationshipExists(relationship.getRelationship())) {
                    update.add(relationship);
                } else {
                    create.add(relationship);
                }
            } else {
                String message = String.format("Can't update relationship '%s': TrackedEntityInstance '%s' is not the owner of the relationship", relationship.getRelationship(), daoEntityInstance.getUid());
                importSummaries.addImportSummary(new ImportSummary(ImportStatus.ERROR, message).setReference(relationship.getRelationship()).incrementIgnored());
            }
        }
    }
    importSummaries.addImportSummaries(relationshipService.addRelationships(create, importOptions));
    importSummaries.addImportSummaries(relationshipService.updateRelationships(update, importOptions));
    importSummaries.addImportSummaries(relationshipService.deleteRelationships(delete, importOptions));
    return importSummaries;
}
Also used : ImportStrategy(org.hisp.dhis.importexport.ImportStrategy) Authorities(org.hisp.dhis.security.Authorities) Date(java.util.Date) Restrictions(org.hisp.dhis.query.Restrictions) TrackedEntityAttributeValueService(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValueService) TrackedEntityInstanceAuditService(org.hisp.dhis.trackedentity.TrackedEntityInstanceAuditService) ReservedValueService(org.hisp.dhis.reservedvalue.ReservedValueService) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) StringUtils(org.apache.commons.lang3.StringUtils) TrackedEntityAttributeService(org.hisp.dhis.trackedentity.TrackedEntityAttributeService) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) RelationshipService(org.hisp.dhis.relationship.RelationshipService) FileResourceService(org.hisp.dhis.fileresource.FileResourceService) Map(java.util.Map) ProgramInstance(org.hisp.dhis.program.ProgramInstance) JobConfiguration(org.hisp.dhis.scheduling.JobConfiguration) TrackedEntityAttributeStore(org.hisp.dhis.trackedentity.TrackedEntityAttributeStore) EnrollmentService(org.hisp.dhis.dxf2.events.enrollment.EnrollmentService) Query(org.hisp.dhis.query.Query) UserService(org.hisp.dhis.user.UserService) TrackedEntityInstanceQueryParams(org.hisp.dhis.trackedentity.TrackedEntityInstanceQueryParams) Collection(java.util.Collection) Set(java.util.Set) SchemaService(org.hisp.dhis.schema.SchemaService) Collectors(java.util.stream.Collectors) QueryService(org.hisp.dhis.query.QueryService) TrackedEntityProgramOwner(org.hisp.dhis.trackedentity.TrackedEntityProgramOwner) ImportReportMode(org.hisp.dhis.dxf2.metadata.feedback.ImportReportMode) Objects(java.util.Objects) TrackerOwnershipManager(org.hisp.dhis.trackedentity.TrackerOwnershipManager) TEA_VALUE_MAX_LENGTH(org.hisp.dhis.trackedentity.TrackedEntityAttributeService.TEA_VALUE_MAX_LENGTH) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) TrackerAccessManager(org.hisp.dhis.trackedentity.TrackerAccessManager) ProgramInstanceService(org.hisp.dhis.program.ProgramInstanceService) Optional(java.util.Optional) TrackedEntityType(org.hisp.dhis.trackedentity.TrackedEntityType) Geometry(org.locationtech.jts.geom.Geometry) Enrollment(org.hisp.dhis.dxf2.events.enrollment.Enrollment) TrackedEntityAttribute(org.hisp.dhis.trackedentity.TrackedEntityAttribute) TrackedEntityInstanceAggregate(org.hisp.dhis.dxf2.events.aggregates.TrackedEntityInstanceAggregate) TrackedEntityTypeService(org.hisp.dhis.trackedentity.TrackedEntityTypeService) Constants(org.hisp.dhis.dxf2.Constants) AuditType(org.hisp.dhis.common.AuditType) GeoUtils(org.hisp.dhis.system.util.GeoUtils) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) Program(org.hisp.dhis.program.Program) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Notifier(org.hisp.dhis.system.notification.Notifier) RelationshipParams(org.hisp.dhis.dxf2.events.RelationshipParams) Lists(com.google.common.collect.Lists) IdentifiableObjectManager(org.hisp.dhis.common.IdentifiableObjectManager) DbmsManager(org.hisp.dhis.dbms.DbmsManager) ImportConflicts(org.hisp.dhis.dxf2.importsummary.ImportConflicts) User(org.hisp.dhis.user.User) ImportStatus(org.hisp.dhis.dxf2.importsummary.ImportStatus) TrackedEntityInstanceAudit(org.hisp.dhis.audit.payloads.TrackedEntityInstanceAudit) IdSchemes(org.hisp.dhis.common.IdSchemes) FileResource(org.hisp.dhis.fileresource.FileResource) TrackedEntityInstanceParams(org.hisp.dhis.dxf2.events.TrackedEntityInstanceParams) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) ImportOptions(org.hisp.dhis.dxf2.common.ImportOptions) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) DebugUtils(org.hisp.dhis.commons.util.DebugUtils) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) FeatureType(org.hisp.dhis.organisationunit.FeatureType) NotificationLevel(org.hisp.dhis.system.notification.NotificationLevel) RelationshipItem(org.hisp.dhis.relationship.RelationshipItem) CurrentUserService(org.hisp.dhis.user.CurrentUserService) CachingMap(org.hisp.dhis.commons.collection.CachingMap) ERROR(org.hisp.dhis.system.notification.NotificationLevel.ERROR) CodeGenerator(org.hisp.dhis.common.CodeGenerator) Collections(java.util.Collections) DateUtils(org.hisp.dhis.util.DateUtils) Transactional(org.springframework.transaction.annotation.Transactional) ImportSummary(org.hisp.dhis.dxf2.importsummary.ImportSummary) ArrayList(java.util.ArrayList) ImportSummaries(org.hisp.dhis.dxf2.importsummary.ImportSummaries) RelationshipItem(org.hisp.dhis.relationship.RelationshipItem)

Example 27 with RelationshipItem

use of org.hisp.dhis.relationship.RelationshipItem in project dhis2-core by dhis2.

the class AbstractRelationshipService method createDAORelationship.

private org.hisp.dhis.relationship.Relationship createDAORelationship(Relationship relationship) {
    RelationshipType relationshipType = relationshipTypeCache.get(relationship.getRelationshipType());
    org.hisp.dhis.relationship.Relationship daoRelationship = new org.hisp.dhis.relationship.Relationship();
    RelationshipItem fromItem = null;
    RelationshipItem toItem = null;
    daoRelationship.setRelationshipType(relationshipType);
    if (relationship.getRelationship() != null) {
        daoRelationship.setUid(relationship.getRelationship());
    }
    // FROM
    if (relationshipType.getFromConstraint().getRelationshipEntity().equals(TRACKED_ENTITY_INSTANCE)) {
        fromItem = new RelationshipItem();
        fromItem.setTrackedEntityInstance(trackedEntityInstanceCache.get(getUidOfRelationshipItem(relationship.getFrom())));
    } else if (relationshipType.getFromConstraint().getRelationshipEntity().equals(PROGRAM_INSTANCE)) {
        fromItem = new RelationshipItem();
        fromItem.setProgramInstance(programInstanceCache.get(getUidOfRelationshipItem(relationship.getFrom())));
    } else if (relationshipType.getFromConstraint().getRelationshipEntity().equals(PROGRAM_STAGE_INSTANCE)) {
        fromItem = new RelationshipItem();
        fromItem.setProgramStageInstance(programStageInstanceCache.get(getUidOfRelationshipItem(relationship.getFrom())));
    }
    // TO
    if (relationshipType.getToConstraint().getRelationshipEntity().equals(TRACKED_ENTITY_INSTANCE)) {
        toItem = new RelationshipItem();
        toItem.setTrackedEntityInstance(trackedEntityInstanceCache.get(getUidOfRelationshipItem(relationship.getTo())));
    } else if (relationshipType.getToConstraint().getRelationshipEntity().equals(PROGRAM_INSTANCE)) {
        toItem = new RelationshipItem();
        toItem.setProgramInstance(programInstanceCache.get(getUidOfRelationshipItem(relationship.getTo())));
    } else if (relationshipType.getToConstraint().getRelationshipEntity().equals(PROGRAM_STAGE_INSTANCE)) {
        toItem = new RelationshipItem();
        toItem.setProgramStageInstance(programStageInstanceCache.get(getUidOfRelationshipItem(relationship.getTo())));
    }
    daoRelationship.setFrom(fromItem);
    daoRelationship.setTo(toItem);
    daoRelationship.setKey(RelationshipUtils.generateRelationshipKey(daoRelationship));
    daoRelationship.setInvertedKey(RelationshipUtils.generateRelationshipInvertedKey(daoRelationship));
    return daoRelationship;
}
Also used : Relationship(org.hisp.dhis.dxf2.events.trackedentity.Relationship) RelationshipType(org.hisp.dhis.relationship.RelationshipType) RelationshipItem(org.hisp.dhis.relationship.RelationshipItem)

Example 28 with RelationshipItem

use of org.hisp.dhis.relationship.RelationshipItem in project dhis2-core by dhis2.

the class TrackerTest method persistRelationship.

public Relationship persistRelationship(TrackedEntityInstance tei, ProgramInstance pi) {
    RelationshipItem from = new RelationshipItem();
    from.setTrackedEntityInstance(tei);
    RelationshipItem to = new RelationshipItem();
    to.setProgramInstance(pi);
    return _persistRelationship(from, to);
}
Also used : RelationshipItem(org.hisp.dhis.relationship.RelationshipItem)

Example 29 with RelationshipItem

use of org.hisp.dhis.relationship.RelationshipItem in project dhis2-core by dhis2.

the class DeduplicationHelper method getInvalidReferenceErrors.

public String getInvalidReferenceErrors(DeduplicationMergeParams params) {
    TrackedEntityInstance original = params.getOriginal();
    TrackedEntityInstance duplicate = params.getDuplicate();
    MergeObject mergeObject = params.getMergeObject();
    /*
         * Step 1: Make sure all uids in mergeObject is valid
         */
    List<String> uids = ListUtils.distinctUnion(mergeObject.getTrackedEntityAttributes(), mergeObject.getEnrollments(), mergeObject.getRelationships());
    for (String uid : uids) {
        if (!CodeGenerator.isValidUid(uid)) {
            return "Invalid uid '" + uid + "'.";
        }
    }
    /*
         * Step 2: Make sure all references objects exists in duplicate
         */
    Set<String> validTrackedEntityAttributes = duplicate.getTrackedEntityAttributeValues().stream().map(teav -> teav.getAttribute().getUid()).collect(Collectors.toSet());
    Set<String> validRelationships = duplicate.getRelationshipItems().stream().map(rel -> rel.getRelationship().getUid()).collect(Collectors.toSet());
    Set<String> validEnrollments = duplicate.getProgramInstances().stream().map(BaseIdentifiableObject::getUid).collect(Collectors.toSet());
    for (String tea : mergeObject.getTrackedEntityAttributes()) {
        if (!validTrackedEntityAttributes.contains(tea)) {
            return "Duplicate has no attribute '" + tea + "'.";
        }
    }
    String rel = mergeObject.getRelationships().stream().filter(r -> !validRelationships.contains(r)).findFirst().orElse(null);
    if (rel != null) {
        return "Duplicate has no relationship '" + rel + "'.";
    }
    for (String enrollmentUid : mergeObject.getEnrollments()) {
        if (!validEnrollments.contains(enrollmentUid)) {
            return "Duplicate has no enrollment '" + enrollmentUid + "'.";
        }
    }
    /*
         * Step 3: Duplicate Relationships and Enrollments
         */
    Set<Relationship> relationshipsToMerge = params.getDuplicate().getRelationshipItems().stream().map(RelationshipItem::getRelationship).filter(r -> mergeObject.getRelationships().contains(r.getUid())).collect(Collectors.toSet());
    String duplicateRelationshipError = getDuplicateRelationshipError(params.getOriginal(), relationshipsToMerge);
    if (duplicateRelationshipError != null) {
        return "Invalid relationship '" + duplicateRelationshipError + "'. A similar relationship already exists on original.";
    }
    Set<String> programUidOfExistingEnrollments = original.getProgramInstances().stream().map(ProgramInstance::getProgram).map(BaseIdentifiableObject::getUid).collect(Collectors.toSet());
    String duplicateEnrollment = duplicate.getProgramInstances().stream().filter(pi -> mergeObject.getEnrollments().contains(pi.getUid())).map(ProgramInstance::getProgram).map(BaseIdentifiableObject::getUid).filter(programUidOfExistingEnrollments::contains).findAny().orElse(null);
    if (duplicateEnrollment != null) {
        return "Invalid enrollment '" + duplicateEnrollment + "'. A similar enrollment already exists on original.";
    }
    /*
         * Step 4: Make sure no relationships will become self-referencing.
         */
    Set<String> relationshipsToMergeUids = relationshipsToMerge.stream().map(BaseIdentifiableObject::getUid).collect(Collectors.toSet());
    String selfReferencingRelationship = original.getRelationshipItems().stream().map(RelationshipItem::getRelationship).map(BaseIdentifiableObject::getUid).filter(relationshipsToMergeUids::contains).findFirst().orElse(null);
    if (selfReferencingRelationship != null) {
        return "Invalid relationship '" + selfReferencingRelationship + "'. Relationship is between original and duplicate.";
    }
    return null;
}
Also used : IdentifiableObject(org.hisp.dhis.common.IdentifiableObject) BaseIdentifiableObject(org.hisp.dhis.common.BaseIdentifiableObject) ListUtils(org.hisp.dhis.commons.collection.ListUtils) RequiredArgsConstructor(lombok.RequiredArgsConstructor) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) Set(java.util.Set) TrackedEntityAttributeValue(org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue) OrganisationUnitService(org.hisp.dhis.organisationunit.OrganisationUnitService) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) ObjectUtils(org.hisp.dhis.util.ObjectUtils) List(java.util.List) Component(org.springframework.stereotype.Component) RelationshipItem(org.hisp.dhis.relationship.RelationshipItem) RelationshipService(org.hisp.dhis.relationship.RelationshipService) CurrentUserService(org.hisp.dhis.user.CurrentUserService) Map(java.util.Map) RelationshipType(org.hisp.dhis.relationship.RelationshipType) ProgramInstance(org.hisp.dhis.program.ProgramInstance) ProgramInstanceService(org.hisp.dhis.program.ProgramInstanceService) AclService(org.hisp.dhis.security.acl.AclService) User(org.hisp.dhis.user.User) CodeGenerator(org.hisp.dhis.common.CodeGenerator) Relationship(org.hisp.dhis.relationship.Relationship) Relationship(org.hisp.dhis.relationship.Relationship) ProgramInstance(org.hisp.dhis.program.ProgramInstance) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance) RelationshipItem(org.hisp.dhis.relationship.RelationshipItem)

Example 30 with RelationshipItem

use of org.hisp.dhis.relationship.RelationshipItem in project dhis2-core by dhis2.

the class MaintenanceServiceTest method testDeleteSoftDeletedProgramStageInstanceLinkedToARelationshipItem.

@Test
void testDeleteSoftDeletedProgramStageInstanceLinkedToARelationshipItem() {
    RelationshipType rType = createRelationshipType('A');
    rType.getFromConstraint().setRelationshipEntity(RelationshipEntity.PROGRAM_STAGE_INSTANCE);
    rType.getFromConstraint().setProgram(program);
    rType.getFromConstraint().setProgramStage(program.getProgramStageByStage(1));
    rType.getToConstraint().setRelationshipEntity(RelationshipEntity.TRACKED_ENTITY_INSTANCE);
    rType.getFromConstraint().setTrackedEntityType(entityInstance.getTrackedEntityType());
    relationshipTypeService.addRelationshipType(rType);
    ProgramStageInstance programStageInstanceA = new ProgramStageInstance(programInstance, program.getProgramStageByStage(1));
    programStageInstanceA.setDueDate(enrollmentDate);
    programStageInstanceA.setUid("UID-A");
    long idA = programStageInstanceService.addProgramStageInstance(programStageInstanceA);
    Relationship r = new Relationship();
    RelationshipItem rItem1 = new RelationshipItem();
    rItem1.setProgramStageInstance(programStageInstanceA);
    RelationshipItem rItem2 = new RelationshipItem();
    rItem2.setTrackedEntityInstance(entityInstance);
    r.setFrom(rItem1);
    r.setTo(rItem2);
    r.setRelationshipType(rType);
    r.setKey(RelationshipUtils.generateRelationshipKey(r));
    r.setInvertedKey(RelationshipUtils.generateRelationshipInvertedKey(r));
    relationshipService.addRelationship(r);
    assertNotNull(programStageInstanceService.getProgramStageInstance(idA));
    assertNotNull(relationshipService.getRelationship(r.getId()));
    programStageInstanceService.deleteProgramStageInstance(programStageInstanceA);
    assertNull(programStageInstanceService.getProgramStageInstance(idA));
    assertNull(relationshipService.getRelationship(r.getId()));
    assertTrue(programStageInstanceService.programStageInstanceExistsIncludingDeleted(programStageInstanceA.getUid()));
    maintenanceService.deleteSoftDeletedProgramStageInstances();
    assertFalse(programStageInstanceService.programStageInstanceExistsIncludingDeleted(programStageInstanceA.getUid()));
}
Also used : Relationship(org.hisp.dhis.relationship.Relationship) RelationshipType(org.hisp.dhis.relationship.RelationshipType) ProgramStageInstance(org.hisp.dhis.program.ProgramStageInstance) RelationshipItem(org.hisp.dhis.relationship.RelationshipItem) Test(org.junit.jupiter.api.Test)

Aggregations

RelationshipItem (org.hisp.dhis.relationship.RelationshipItem)30 Relationship (org.hisp.dhis.relationship.Relationship)16 Test (org.junit.jupiter.api.Test)11 TrackedEntityInstance (org.hisp.dhis.trackedentity.TrackedEntityInstance)9 RelationshipType (org.hisp.dhis.relationship.RelationshipType)8 DhisConvenienceTest (org.hisp.dhis.DhisConvenienceTest)7 ArrayList (java.util.ArrayList)5 ProgramInstance (org.hisp.dhis.program.ProgramInstance)5 ProgramStageInstance (org.hisp.dhis.program.ProgramStageInstance)4 Date (java.util.Date)3 TrackedEntityAttributeValue (org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue)3 HashSet (java.util.HashSet)2 List (java.util.List)2 Map (java.util.Map)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 CodeGenerator (org.hisp.dhis.common.CodeGenerator)2 IllegalQueryException (org.hisp.dhis.common.IllegalQueryException)2 ProgramInstanceService (org.hisp.dhis.program.ProgramInstanceService)2 RelationshipService (org.hisp.dhis.relationship.RelationshipService)2