use of org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance in project dhis2-core by dhis2.
the class TrackedEntityInstanceController method getTrackedEntityInstances.
// -------------------------------------------------------------------------
// READ
// -------------------------------------------------------------------------
@RequestMapping(value = "", method = RequestMethod.GET)
@ResponseBody
public RootNode getTrackedEntityInstances(@RequestParam(required = false) String query, @RequestParam(required = false) Set<String> attribute, @RequestParam(required = false) Set<String> filter, @RequestParam(required = false) String ou, @RequestParam(required = false) OrganisationUnitSelectionMode ouMode, @RequestParam(required = false) String program, @RequestParam(required = false) ProgramStatus programStatus, @RequestParam(required = false) Boolean followUp, @RequestParam(required = false) Date lastUpdatedStartDate, @RequestParam(required = false) Date lastUpdatedEndDate, @RequestParam(required = false) Date programStartDate, @RequestParam(required = false) Date programEnrollmentStartDate, @RequestParam(required = false) Date programEndDate, @RequestParam(required = false) Date programEnrollmentEndDate, @RequestParam(required = false) Date programIncidentStartDate, @RequestParam(required = false) Date programIncidentEndDate, @RequestParam(required = false) String trackedEntity, @RequestParam(required = false) String trackedEntityInstance, @RequestParam(required = false) EventStatus eventStatus, @RequestParam(required = false) Date eventStartDate, @RequestParam(required = false) Date eventEndDate, @RequestParam(required = false) boolean skipMeta, @RequestParam(required = false) Integer page, @RequestParam(required = false) Integer pageSize, @RequestParam(required = false) boolean totalPages, @RequestParam(required = false) boolean skipPaging, @RequestParam(required = false) boolean includeDeleted, @RequestParam(required = false) String order) throws Exception {
programEnrollmentStartDate = ObjectUtils.firstNonNull(programEnrollmentStartDate, programStartDate);
programEnrollmentEndDate = ObjectUtils.firstNonNull(programEnrollmentEndDate, programEndDate);
List<String> fields = Lists.newArrayList(contextService.getParameterValues("fields"));
if (fields.isEmpty()) {
fields.add(":all");
}
Set<String> orgUnits = TextUtils.splitToArray(ou, TextUtils.SEMICOLON);
RootNode rootNode = NodeUtils.createMetadata();
List<TrackedEntityInstance> trackedEntityInstances;
TrackedEntityInstanceQueryParams queryParams = instanceService.getFromUrl(query, attribute, filter, orgUnits, ouMode, program, programStatus, followUp, lastUpdatedStartDate, lastUpdatedEndDate, programEnrollmentStartDate, programEnrollmentEndDate, programIncidentStartDate, programIncidentEndDate, trackedEntity, eventStatus, eventStartDate, eventEndDate, skipMeta, page, pageSize, totalPages, skipPaging, includeDeleted, getOrderParams(order));
if (trackedEntityInstance == null) {
trackedEntityInstances = trackedEntityInstanceService.getTrackedEntityInstances(queryParams, getTrackedEntityInstanceParams(fields));
} else {
Set<String> trackedEntityInstanceIds = TextUtils.splitToArray(trackedEntityInstance, TextUtils.SEMICOLON);
trackedEntityInstances = trackedEntityInstanceIds != null ? trackedEntityInstanceIds.stream().map(id -> trackedEntityInstanceService.getTrackedEntityInstance(id, getTrackedEntityInstanceParams(fields))).collect(Collectors.toList()) : null;
}
if (queryParams.isPaging() && queryParams.isTotalPages()) {
int count = trackedEntityInstanceService.getTrackedEntityInstanceCount(queryParams);
Pager pager = new Pager(queryParams.getPageWithDefault(), count, queryParams.getPageSizeWithDefault());
rootNode.addChild(NodeUtils.createPager(pager));
}
rootNode.addChild(fieldFilterService.filter(TrackedEntityInstance.class, trackedEntityInstances, fields));
return rootNode;
}
use of org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance in project dhis2-core by dhis2.
the class AbstractEnrollmentService method updateAttributeValues.
private void updateAttributeValues(Enrollment enrollment, ImportOptions importOptions) {
org.hisp.dhis.trackedentity.TrackedEntityInstance trackedEntityInstance = teiService.getTrackedEntityInstance(enrollment.getTrackedEntityInstance());
Map<String, Attribute> attributeValueMap = Maps.newHashMap();
for (Attribute attribute : enrollment.getAttributes()) {
attributeValueMap.put(attribute.getAttribute(), attribute);
}
trackedEntityInstance.getTrackedEntityAttributeValues().stream().filter(value -> attributeValueMap.containsKey(value.getAttribute().getUid())).forEach(value -> {
Attribute enrollmentAttribute = attributeValueMap.get(value.getAttribute().getUid());
String newValue = enrollmentAttribute.getValue();
value.setValue(newValue);
value.setStoredBy(getStoredBy(enrollmentAttribute, importOptions.getUser()));
trackedEntityAttributeValueService.updateTrackedEntityAttributeValue(value, importOptions.getUser());
attributeValueMap.remove(value.getAttribute().getUid());
});
for (String key : attributeValueMap.keySet()) {
TrackedEntityAttribute attribute = getTrackedEntityAttribute(importOptions.getIdSchemes(), key);
if (attribute != null) {
TrackedEntityAttributeValue value = new TrackedEntityAttributeValue();
Attribute enrollmentAttribute = attributeValueMap.get(key);
value.setValue(enrollmentAttribute.getValue());
value.setAttribute(attribute);
value.setStoredBy(getStoredBy(enrollmentAttribute, importOptions.getUser()));
trackedEntityAttributeValueService.addTrackedEntityAttributeValue(value);
trackedEntityInstance.addAttributeValue(value);
}
}
}
use of org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance in project dhis2-core by dhis2.
the class TrackedEntityInstanceAggregate method find.
/**
* Fetches a List of {@see TrackedEntityInstance} based on the list of
* primary keys and search parameters
*
* @param ids a List of {@see TrackedEntityInstance} Primary Keys
* @param params an instance of {@see TrackedEntityInstanceParams}
*
* @return a List of {@see TrackedEntityInstance} objects
*/
public List<TrackedEntityInstance> find(List<Long> ids, TrackedEntityInstanceParams params, TrackedEntityInstanceQueryParams queryParams) {
final User user = currentUserService.getCurrentUser();
if (!userGroupUIDCache.get(user.getUid()).isPresent() && !CollectionUtils.isEmpty(user.getGroups())) {
userGroupUIDCache.put(user.getUid(), user.getGroups().stream().map(group -> group.getUid()).collect(Collectors.toList()));
}
/*
* Create a context with information which will be used to fetch the
* entities
*/
AggregateContext ctx = securityCache.get(user.getUid(), userUID -> getSecurityContext(userUID, userGroupUIDCache.get(userUID).orElse(Lists.newArrayList()))).toBuilder().userId(user.getId()).superUser(user.isSuper()).params(params).queryParams(queryParams).build();
/*
* Async fetch Relationships for the given TrackedEntityInstance id
* (only if isIncludeRelationships = true)
*/
final CompletableFuture<Multimap<String, Relationship>> relationshipsAsync = conditionalAsyncFetch(ctx.getParams().isIncludeRelationships(), () -> trackedEntityInstanceStore.getRelationships(ids), getPool());
/*
* Async fetch Enrollments for the given TrackedEntityInstance id (only
* if isIncludeEnrollments = true)
*/
final CompletableFuture<Multimap<String, Enrollment>> enrollmentsAsync = conditionalAsyncFetch(ctx.getParams().isIncludeEnrollments(), () -> enrollmentAggregate.findByTrackedEntityInstanceIds(ids, ctx), getPool());
/*
* Async fetch all ProgramOwner for the given TrackedEntityInstance id
*/
final CompletableFuture<Multimap<String, ProgramOwner>> programOwnersAsync = conditionalAsyncFetch(ctx.getParams().isIncludeProgramOwners(), () -> trackedEntityInstanceStore.getProgramOwners(ids), getPool());
/*
* Async Fetch TrackedEntityInstances by id
*/
final CompletableFuture<Map<String, TrackedEntityInstance>> teisAsync = supplyAsync(() -> trackedEntityInstanceStore.getTrackedEntityInstances(ids, ctx), getPool());
/*
* Async fetch TrackedEntityInstance Attributes by TrackedEntityInstance
* id
*/
final CompletableFuture<Multimap<String, Attribute>> attributesAsync = supplyAsync(() -> trackedEntityInstanceStore.getAttributes(ids), getPool());
/*
* Async fetch Owned Tei mapped to the provided program attributes by
* TrackedEntityInstance id
*/
final CompletableFuture<Multimap<String, String>> ownedTeiAsync = supplyAsync(() -> trackedEntityInstanceStore.getOwnedTeis(ids, ctx), getPool());
/*
* Execute all queries and merge the results
*/
return allOf(teisAsync, attributesAsync, relationshipsAsync, enrollmentsAsync, ownedTeiAsync).thenApplyAsync(fn -> {
Map<String, TrackedEntityInstance> teis = teisAsync.join();
Multimap<String, Attribute> attributes = attributesAsync.join();
Multimap<String, Relationship> relationships = relationshipsAsync.join();
Multimap<String, Enrollment> enrollments = enrollmentsAsync.join();
Multimap<String, ProgramOwner> programOwners = programOwnersAsync.join();
Multimap<String, String> ownedTeis = ownedTeiAsync.join();
Stream<String> teiUidStream = teis.keySet().parallelStream();
if (queryParams.hasProgram()) {
teiUidStream = teiUidStream.filter(ownedTeis::containsKey);
}
return teiUidStream.map(uid -> {
TrackedEntityInstance tei = teis.get(uid);
tei.setAttributes(filterAttributes(attributes.get(uid), ownedTeis.get(uid), teiAttributesCache.get("ALL_ATTRIBUTES", s -> trackedEntityAttributeService.getTrackedEntityAttributesByTrackedEntityTypes()), programTeiAttributesCache.get("ATTRIBUTES_BY_PROGRAM", s -> trackedEntityAttributeService.getTrackedEntityAttributesByProgram()), ctx));
tei.setRelationships(new ArrayList<>(relationships.get(uid)));
tei.setEnrollments(filterEnrollments(enrollments.get(uid), ownedTeis.get(uid), ctx));
tei.setProgramOwners(new ArrayList<>(programOwners.get(uid)));
return tei;
}).collect(Collectors.toList());
}, getPool()).join();
}
use of org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance in project dhis2-core by dhis2.
the class ProgramInstanceSupplier method mapEventsToProgramInstanceByTei.
/**
* Loop through the events and check if there is any event left without a
* Program Instance: for each Event without a PI, try to fetch the Program
* Instance by Program and Tracked Entity Instance
*/
private void mapEventsToProgramInstanceByTei(ImportOptions importOptions, List<Event> events, Map<String, ProgramInstance> programInstances, Map<String, Pair<TrackedEntityInstance, Boolean>> teiMap) {
for (Event event : events) {
if (!programInstances.containsKey(event.getUid())) {
Pair<TrackedEntityInstance, Boolean> teiPair = teiMap.get(event.getUid());
Program program = getProgramByUid(event.getProgram(), programSupplier.get(importOptions, events).values());
if (teiPair != null && program != null) {
TrackedEntityInstance tei = teiPair.getKey();
ProgramInstance programInstance = getByTeiAndProgram(importOptions, tei.getId(), program.getId(), event);
if (programInstance != null) {
programInstances.put(event.getUid(), programInstance);
}
}
}
}
}
use of org.hisp.dhis.dxf2.events.trackedentity.TrackedEntityInstance in project dhis2-core by dhis2.
the class WorkContextLoader method load.
@Transactional(readOnly = true)
public WorkContext load(ImportOptions importOptions, List<Event> events) {
sessionFactory.getCurrentSession().flush();
ImportOptions localImportOptions = importOptions;
// API allows a null Import Options
if (localImportOptions == null) {
localImportOptions = ImportOptions.getDefaultImportOptions();
}
initializeUser(localImportOptions);
// Make sure all events have the 'uid' field populated
events = uidGen.assignUidToEvents(events);
final Map<String, ProgramStageInstance> programStageInstanceMap = programStageInstanceSupplier.get(localImportOptions, events);
final Map<String, Pair<TrackedEntityInstance, Boolean>> teiMap = trackedEntityInstanceSupplier.get(localImportOptions, events);
final Map<String, OrganisationUnit> orgUniMap = organisationUnitSupplier.get(localImportOptions, events);
return WorkContext.builder().importOptions(localImportOptions).programsMap(programSupplier.get(localImportOptions, events)).programStageInstanceMap(programStageInstanceMap).organisationUnitMap(orgUniMap).trackedEntityInstanceMap(teiMap).programInstanceMap(programInstanceSupplier.get(localImportOptions, teiMap, events)).categoryOptionComboMap(categoryOptionComboSupplier.get(localImportOptions, events)).dataElementMap(dataElementSupplier.get(localImportOptions, events)).notesMap(noteSupplier.get(localImportOptions, events)).assignedUserMap(assignedUserSupplier.get(localImportOptions, events)).eventDataValueMap(new EventDataValueAggregator().aggregateDataValues(events, programStageInstanceMap, localImportOptions)).programWithOrgUnitsMap(programOrgUnitSupplier.get(localImportOptions, events, orgUniMap)).serviceDelegator(serviceDelegatorSupplier.get()).build();
}
Aggregations