Search in sources :

Example 1 with IllegalQueryException

use of org.hisp.dhis.common.IllegalQueryException in project dhis2-core by dhis2.

the class AbstractEventService method validateExpiryDays.

private void validateExpiryDays(Event event, Program program, ProgramStageInstance programStageInstance) {
    if (program != null) {
        if (program.getCompleteEventsExpiryDays() > 0) {
            if (event.getStatus() == EventStatus.COMPLETED || programStageInstance != null && programStageInstance.getStatus() == EventStatus.COMPLETED) {
                Date referenceDate = null;
                if (programStageInstance != null) {
                    referenceDate = programStageInstance.getCompletedDate();
                } else {
                    if (event.getCompletedDate() != null) {
                        referenceDate = DateUtils.parseDate(event.getCompletedDate());
                    }
                }
                if (referenceDate == null) {
                    throw new IllegalQueryException("Event needs to have completed date.");
                }
                if ((new Date()).after(DateUtils.getDateAfterAddition(referenceDate, program.getCompleteEventsExpiryDays()))) {
                    throw new IllegalQueryException("The event's completness date has expired. Not possible to make changes to this event");
                }
            }
        }
        PeriodType periodType = program.getExpiryPeriodType();
        if (periodType != null && program.getExpiryDays() > 0) {
            if (programStageInstance != null) {
                Date today = new Date();
                if (programStageInstance.getExecutionDate() == null) {
                    throw new IllegalQueryException("Event needs to have event date.");
                }
                Period period = periodType.createPeriod(programStageInstance.getExecutionDate());
                if (today.after(DateUtils.getDateAfterAddition(period.getEndDate(), program.getExpiryDays()))) {
                    throw new IllegalQueryException("The program's expiry date has passed. It is not possible to make changes to this event.");
                }
            } else {
                String referenceDate = event.getEventDate() != null ? event.getEventDate() : event.getDueDate() != null ? event.getDueDate() : null;
                if (referenceDate == null) {
                    throw new IllegalQueryException("Event needs to have at least one (event or schedule) date. ");
                }
                Period period = periodType.createPeriod(new Date());
                if (DateUtils.parseDate(referenceDate).before(period.getStartDate())) {
                    throw new IllegalQueryException("The event's date belongs to an expired period. It is not possble to create such event.");
                }
            }
        }
    }
}
Also used : PeriodType(org.hisp.dhis.period.PeriodType) Period(org.hisp.dhis.period.Period) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) Date(java.util.Date)

Example 2 with IllegalQueryException

use of org.hisp.dhis.common.IllegalQueryException in project dhis2-core by dhis2.

the class AbstractEventService method getFromUrl.

@Override
public EventSearchParams getFromUrl(String program, String programStage, ProgramStatus programStatus, Boolean followUp, String orgUnit, OrganisationUnitSelectionMode orgUnitSelectionMode, String trackedEntityInstance, Date startDate, Date endDate, Date dueDateStart, Date dueDateEnd, Date lastUpdatedStartDate, Date lastUpdatedEndDate, EventStatus status, DataElementCategoryOptionCombo attributeOptionCombo, IdSchemes idSchemes, Integer page, Integer pageSize, boolean totalPages, boolean skipPaging, List<Order> orders, List<String> gridOrders, boolean includeAttributes, Set<String> events, Set<String> filters, Set<String> dataElements, boolean includeDeleted) {
    UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials();
    EventSearchParams params = new EventSearchParams();
    Program pr = programService.getProgram(program);
    if (StringUtils.isNotEmpty(program) && pr == null) {
        throw new IllegalQueryException("Program is specified but does not exist: " + program);
    }
    ProgramStage ps = programStageService.getProgramStage(programStage);
    if (StringUtils.isNotEmpty(programStage) && ps == null) {
        throw new IllegalQueryException("Program stage is specified but does not exist: " + programStage);
    }
    OrganisationUnit ou = organisationUnitService.getOrganisationUnit(orgUnit);
    if (StringUtils.isNotEmpty(orgUnit) && ou == null) {
        throw new IllegalQueryException("Org unit is specified but does not exist: " + orgUnit);
    }
    if (ou != null && !organisationUnitService.isInUserHierarchy(ou)) {
        if (!userCredentials.isSuper() && !userCredentials.isAuthorized("F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS")) {
            throw new IllegalQueryException("User has no access to organisation unit: " + ou.getUid());
        }
    }
    if (pr != null && !userCredentials.isSuper() && !userCredentials.canAccessProgram(pr)) {
        throw new IllegalQueryException("User has no access to program: " + pr.getUid());
    }
    TrackedEntityInstance tei = entityInstanceService.getTrackedEntityInstance(trackedEntityInstance);
    if (StringUtils.isNotEmpty(trackedEntityInstance) && tei == null) {
        throw new IllegalQueryException("Tracked entity instance is specified but does not exist: " + trackedEntityInstance);
    }
    if (events != null && filters != null) {
        throw new IllegalQueryException("Event UIDs and filters can not be specified at the same time");
    }
    if (events == null) {
        events = new HashSet<>();
    }
    if (filters != null) {
        if (StringUtils.isNotEmpty(programStage) && ps == null) {
            throw new IllegalQueryException("ProgramStage needs to be specified for event filtering to work");
        }
        for (String filter : filters) {
            QueryItem item = getQueryItem(filter);
            params.getFilters().add(item);
        }
    }
    if (dataElements != null) {
        for (String de : dataElements) {
            QueryItem dataElement = getQueryItem(de);
            params.getDataElements().add(dataElement);
        }
    }
    params.setProgram(pr);
    params.setProgramStage(ps);
    params.setOrgUnit(ou);
    params.setTrackedEntityInstance(tei);
    params.setProgramStatus(programStatus);
    params.setFollowUp(followUp);
    params.setOrgUnitSelectionMode(orgUnitSelectionMode);
    params.setStartDate(startDate);
    params.setEndDate(endDate);
    params.setDueDateStart(dueDateStart);
    params.setDueDateEnd(dueDateEnd);
    params.setLastUpdatedStartDate(lastUpdatedStartDate);
    params.setLastUpdatedEndDate(lastUpdatedEndDate);
    params.setEventStatus(status);
    params.setCategoryOptionCombo(attributeOptionCombo);
    params.setIdSchemes(idSchemes);
    params.setPage(page);
    params.setPageSize(pageSize);
    params.setTotalPages(totalPages);
    params.setSkipPaging(skipPaging);
    params.setIncludeAttributes(includeAttributes);
    params.setOrders(orders);
    params.setGridOrders(gridOrders);
    params.setEvents(events);
    params.setIncludeDeleted(includeDeleted);
    return params;
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) QueryItem(org.hisp.dhis.common.QueryItem) Program(org.hisp.dhis.program.Program) EventSearchParams(org.hisp.dhis.dxf2.events.event.EventSearchParams) UserCredentials(org.hisp.dhis.user.UserCredentials) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) ProgramStage(org.hisp.dhis.program.ProgramStage) TrackedEntityInstance(org.hisp.dhis.trackedentity.TrackedEntityInstance)

Example 3 with IllegalQueryException

use of org.hisp.dhis.common.IllegalQueryException in project dhis2-core by dhis2.

the class InputUtils method getAttributeOptionCombo.

/**
     * Validates and retrieves the attribute option combo. 409 conflict as
     * status code along with a textual message will be set on the response in
     * case of invalid input.
     *
     * @param cc the category combo identifier.
     * @param cp the category and option query string.
     * @param skipFallback whether to skip fallback to default option combo if
     *        attribute option combo is not found.
     * @return the attribute option combo identified from the given input, or
     *         null. if the input was invalid.
     */
public DataElementCategoryOptionCombo getAttributeOptionCombo(String cc, String cp, boolean skipFallback) {
    Set<String> opts = TextUtils.splitToArray(cp, TextUtils.SEMICOLON);
    if ((cc == null && opts != null || (cc != null && opts == null))) {
        throw new IllegalQueryException("Both or none of category combination and category options must be present");
    }
    DataElementCategoryCombo categoryCombo = null;
    if (cc != null && (categoryCombo = idObjectManager.get(DataElementCategoryCombo.class, cc)) == null) {
        throw new IllegalQueryException("Illegal category combo identifier: " + cc);
    }
    if (categoryCombo == null && opts == null) {
        if (skipFallback) {
            return null;
        }
        categoryCombo = categoryService.getDefaultDataElementCategoryCombo();
    }
    return getAttributeOptionCombo(categoryCombo, cp, null, IdScheme.UID);
}
Also used : DataElementCategoryCombo(org.hisp.dhis.dataelement.DataElementCategoryCombo) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException)

Example 4 with IllegalQueryException

use of org.hisp.dhis.common.IllegalQueryException in project dhis2-core by dhis2.

the class AbstractEventService method convertProgramStageInstance.

private Event convertProgramStageInstance(ProgramStageInstance programStageInstance) {
    if (programStageInstance == null) {
        return null;
    }
    Event event = new Event();
    event.setEvent(programStageInstance.getUid());
    if (programStageInstance.getProgramInstance().getEntityInstance() != null) {
        event.setTrackedEntityInstance(programStageInstance.getProgramInstance().getEntityInstance().getUid());
    }
    event.setFollowup(programStageInstance.getProgramInstance().getFollowup());
    event.setEnrollmentStatus(EnrollmentStatus.fromProgramStatus(programStageInstance.getProgramInstance().getStatus()));
    event.setStatus(programStageInstance.getStatus());
    event.setEventDate(DateUtils.getIso8601NoTz(programStageInstance.getExecutionDate()));
    event.setDueDate(DateUtils.getIso8601NoTz(programStageInstance.getDueDate()));
    event.setStoredBy(programStageInstance.getStoredBy());
    event.setCompletedBy(programStageInstance.getCompletedBy());
    event.setCompletedDate(DateUtils.getIso8601NoTz(programStageInstance.getCompletedDate()));
    event.setCreated(DateUtils.getIso8601NoTz(programStageInstance.getCreated()));
    event.setCreatedAtClient(DateUtils.getIso8601NoTz(programStageInstance.getCreatedAtClient()));
    event.setLastUpdated(DateUtils.getIso8601NoTz(programStageInstance.getLastUpdated()));
    event.setLastUpdatedAtClient(DateUtils.getIso8601NoTz(programStageInstance.getLastUpdatedAtClient()));
    UserCredentials userCredentials = currentUserService.getCurrentUser().getUserCredentials();
    OrganisationUnit ou = programStageInstance.getOrganisationUnit();
    if (ou != null) {
        if (!organisationUnitService.isInUserHierarchy(ou)) {
            if (!userCredentials.isSuper() && !userCredentials.isAuthorized("F_TRACKED_ENTITY_INSTANCE_SEARCH_IN_ALL_ORGUNITS")) {
                throw new IllegalQueryException("User has no access to organisation unit: " + ou.getUid());
            }
        }
        event.setOrgUnit(ou.getUid());
        event.setOrgUnitName(ou.getName());
    }
    Program program = programStageInstance.getProgramInstance().getProgram();
    if (!userCredentials.isSuper() && !userCredentials.getAllPrograms().contains(program)) {
        throw new IllegalQueryException("User has no access to program: " + program.getUid());
    }
    event.setProgram(program.getUid());
    event.setEnrollment(programStageInstance.getProgramInstance().getUid());
    event.setProgramStage(programStageInstance.getProgramStage().getUid());
    event.setAttributeOptionCombo(programStageInstance.getAttributeOptionCombo().getUid());
    event.setAttributeCategoryOptions(String.join(";", programStageInstance.getAttributeOptionCombo().getCategoryOptions().stream().map(DataElementCategoryOption::getUid).collect(Collectors.toList())));
    if (programStageInstance.getProgramInstance().getEntityInstance() != null) {
        event.setTrackedEntityInstance(programStageInstance.getProgramInstance().getEntityInstance().getUid());
    }
    if (programStageInstance.getProgramStage().getCaptureCoordinates()) {
        Coordinate coordinate = null;
        if (programStageInstance.getLongitude() != null && programStageInstance.getLatitude() != null) {
            coordinate = new Coordinate(programStageInstance.getLongitude(), programStageInstance.getLatitude());
            try {
                List<Double> list = OBJECT_MAPPER.readValue(coordinate.getCoordinateString(), new TypeReference<List<Double>>() {
                });
                coordinate.setLongitude(list.get(0));
                coordinate.setLatitude(list.get(1));
            } catch (IOException ignored) {
            }
        }
        if (coordinate != null && coordinate.isValid()) {
            event.setCoordinate(coordinate);
        }
    }
    Collection<TrackedEntityDataValue> dataValues = dataValueService.getTrackedEntityDataValues(programStageInstance);
    for (TrackedEntityDataValue dataValue : dataValues) {
        DataValue value = new DataValue();
        value.setCreated(DateUtils.getIso8601NoTz(dataValue.getCreated()));
        value.setLastUpdated(DateUtils.getIso8601NoTz(dataValue.getLastUpdated()));
        value.setDataElement(dataValue.getDataElement().getUid());
        value.setValue(dataValue.getValue());
        value.setProvidedElsewhere(dataValue.getProvidedElsewhere());
        value.setStoredBy(dataValue.getStoredBy());
        event.getDataValues().add(value);
    }
    List<TrackedEntityComment> comments = programStageInstance.getComments();
    for (TrackedEntityComment comment : comments) {
        Note note = new Note();
        note.setValue(comment.getCommentText());
        note.setStoredBy(comment.getCreator());
        if (comment.getCreatedDate() != null) {
            note.setStoredDate(DateUtils.getIso8601NoTz(comment.getCreatedDate()));
        }
        event.getNotes().add(note);
    }
    return event;
}
Also used : TrackedEntityComment(org.hisp.dhis.trackedentitycomment.TrackedEntityComment) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) Program(org.hisp.dhis.program.Program) TrackedEntityDataValue(org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue) TrackedEntityDataValue(org.hisp.dhis.trackedentitydatavalue.TrackedEntityDataValue) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) IOException(java.io.IOException) UserCredentials(org.hisp.dhis.user.UserCredentials) List(java.util.List) ArrayList(java.util.ArrayList)

Example 5 with IllegalQueryException

use of org.hisp.dhis.common.IllegalQueryException in project dhis2-core by dhis2.

the class DefaultTrackedEntityInstanceService method getQueryItem.

/**
     * Creates a QueryItem from the given item string. Item is on format
     * {attribute-id}:{operator}:{filter-value}[:{operator}:{filter-value}].
     * Only the attribute-id is mandatory.
     */
private QueryItem getQueryItem(String item) {
    String[] split = item.split(DimensionalObject.DIMENSION_NAME_SEP);
    if (split == null || (split.length % 2 != 1)) {
        throw new IllegalQueryException("Query item or filter is invalid: " + item);
    }
    QueryItem queryItem = getItem(split[0]);
    if (// Filters specified
    split.length > 1) {
        for (int i = 1; i < split.length; i += 2) {
            QueryOperator operator = QueryOperator.fromString(split[i]);
            queryItem.getFilters().add(new QueryFilter(operator, split[i + 1]));
        }
    }
    return queryItem;
}
Also used : QueryItem(org.hisp.dhis.common.QueryItem) QueryFilter(org.hisp.dhis.common.QueryFilter) IllegalQueryException(org.hisp.dhis.common.IllegalQueryException) QueryOperator(org.hisp.dhis.common.QueryOperator)

Aggregations

IllegalQueryException (org.hisp.dhis.common.IllegalQueryException)98 Test (org.junit.jupiter.api.Test)26 ErrorMessage (org.hisp.dhis.feedback.ErrorMessage)22 HashSet (java.util.HashSet)17 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)17 User (org.hisp.dhis.user.User)14 QueryItem (org.hisp.dhis.common.QueryItem)13 ArrayList (java.util.ArrayList)12 Date (java.util.Date)11 Program (org.hisp.dhis.program.Program)11 QueryFilter (org.hisp.dhis.common.QueryFilter)10 TrackedEntityInstanceCriteria (org.hisp.dhis.webapi.controller.event.webrequest.TrackedEntityInstanceCriteria)10 Transactional (org.springframework.transaction.annotation.Transactional)10 QueryOperator (org.hisp.dhis.common.QueryOperator)9 List (java.util.List)8 CoreMatchers.containsString (org.hamcrest.CoreMatchers.containsString)8 DataElement (org.hisp.dhis.dataelement.DataElement)8 DhisWebSpringTest (org.hisp.dhis.webapi.DhisWebSpringTest)7 Map (java.util.Map)6 Set (java.util.Set)6