Search in sources :

Example 26 with Category

use of org.hisp.dhis.category.Category in project dhis2-core by dhis2.

the class HibernateValidationResultStore method getUserRestrictions.

/**
 * If we should, restrict which validation results the user is entitled to
 * see, based on the user's organisation units and on the user's dimension
 * constraints if the user has them.
 * <p>
 * If the current user is null (e.g. running a system process or a JUnit
 * test) or superuser, there is no restriction.
 *
 * @param sqlHelper to help with "where" and/or "and" in the where clause.
 * @return String to add restrictions to the HQL query.
 */
private String getUserRestrictions(SqlHelper sqlHelper) {
    final User user = currentUserService.getCurrentUser();
    if (user == null || currentUserService.currentUserIsSuper()) {
        return "";
    }
    StringBuilder restrictions = new StringBuilder();
    // ---------------------------------------------------------------------
    // Restrict by the user's organisation unit sub-trees, if any
    // ---------------------------------------------------------------------
    Set<OrganisationUnit> userOrgUnits = user.getDataViewOrganisationUnitsWithFallback();
    if (!userOrgUnits.isEmpty()) {
        for (OrganisationUnit ou : userOrgUnits) {
            restrictions.append((restrictions.length() == 0 ? " " + sqlHelper.whereAnd() + " (" : " or ") + "locate('" + ou.getUid() + "',vr.organisationUnit.path) <> 0");
        }
        restrictions.append(")");
    }
    // ---------------------------------------------------------------------
    // Restrict by the user's category dimension constraints, if any
    // ---------------------------------------------------------------------
    Set<Category> categories = user.getCatDimensionConstraints();
    if (!isEmpty(categories)) {
        String validCategoryOptionByCategory = isReadable("co", user) + " and exists (select 'x' from Category c where co in elements(c.categoryOptions)" + " and c.id in (" + StringUtils.join(IdentifiableObjectUtils.getIdentifiers(categories), ",") + ") )";
        restrictions.append(" " + sqlHelper.whereAnd() + " 1 = (select min(case when " + validCategoryOptionByCategory + " then 1 else 0 end)" + " from CategoryOption co" + " where co in elements(vr.attributeOptionCombo.categoryOptions) )");
    }
    // ---------------------------------------------------------------------
    // Restrict by the user's cat option group dimension constraints, if any
    // ---------------------------------------------------------------------
    Set<CategoryOptionGroupSet> cogsets = user.getCogsDimensionConstraints();
    if (!isEmpty(cogsets)) {
        String validCategoryOptionByCategoryOptionGroup = "exists (select 'x' from CategoryOptionGroup g" + " join g.groupSets s" + " where g.id in elements(co.groups)" + " and s.id in (" + StringUtils.join(IdentifiableObjectUtils.getIdentifiers(cogsets), ",") + ")" + " and " + isReadable("g", user) + " )";
        restrictions.append(" " + sqlHelper.whereAnd() + " 1 = (select min(case when " + validCategoryOptionByCategoryOptionGroup + " then 1 else 0 end)" + " from CategoryOption co" + " where co in elements(vr.attributeOptionCombo.categoryOptions) )");
    }
    log.debug("Restrictions = " + restrictions);
    return restrictions.toString();
}
Also used : OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) User(org.hisp.dhis.user.User) Category(org.hisp.dhis.category.Category) CategoryOptionGroupSet(org.hisp.dhis.category.CategoryOptionGroupSet)

Example 27 with Category

use of org.hisp.dhis.category.Category in project dhis2-core by dhis2.

the class LoadFormAction method execute.

// -------------------------------------------------------------------------
// Action implementation
// -------------------------------------------------------------------------
@Override
public String execute() throws Exception {
    dataSet = dataSetService.getDataSet(dataSetId);
    if (dataSet == null) {
        return INPUT;
    }
    FormType formType = dataSet.getFormType();
    if (formType.isCustom() && dataSet.hasDataEntryForm()) {
        dataEntryForm = dataSet.getDataEntryForm();
        customDataEntryFormCode = dataEntryFormService.prepareDataEntryFormForEntry(dataEntryForm, dataSet, i18n);
        return formType.toString();
    }
    // ---------------------------------------------------------------------
    // Section / default form
    // ---------------------------------------------------------------------
    List<DataElement> dataElements = new ArrayList<>(dataSet.getDataElements());
    if (dataElements.isEmpty()) {
        return INPUT;
    }
    Collections.sort(dataElements);
    orderedDataElements = ListMap.getListMap(dataElements, de -> de.getDataElementCategoryCombo(dataSet));
    orderedCategoryCombos = getCategoryCombos(dataElements, dataSet);
    User currentUser = currentUserService.getCurrentUser();
    for (CategoryCombo categoryCombo : orderedCategoryCombos) {
        List<CategoryOptionCombo> optionCombos = categoryCombo.getSortedOptionCombos();
        orderedCategoryOptionCombos.put(categoryCombo.getId(), optionCombos);
        addOptionAccess(currentUser, optionComboAccessMap, optionCombos);
        // -----------------------------------------------------------------
        // Perform ordering of categories and their options so that they
        // could be displayed as in the paper form. Note that the total
        // number of entry cells to be generated are the multiple of options
        // from each category.
        // -----------------------------------------------------------------
        numberOfTotalColumns.put(categoryCombo.getId(), optionCombos.size());
        orderedCategories.put(categoryCombo.getId(), categoryCombo.getCategories());
        Map<Long, List<CategoryOption>> optionsMap = new HashMap<>();
        for (Category category : categoryCombo.getCategories()) {
            optionsMap.put(category.getId(), category.getCategoryOptions());
        }
        orderedOptionsMap.put(categoryCombo.getId(), optionsMap);
        // -----------------------------------------------------------------
        // Calculating the number of times each category should be repeated
        // -----------------------------------------------------------------
        Map<Long, Integer> catRepeat = new HashMap<>();
        Map<Long, Collection<Integer>> colRepeat = new HashMap<>();
        int catColSpan = optionCombos.size();
        for (Category cat : categoryCombo.getCategories()) {
            int categoryOptionSize = cat.getCategoryOptions().size();
            if (categoryOptionSize > 0 && catColSpan >= categoryOptionSize) {
                catColSpan = catColSpan / categoryOptionSize;
                int total = optionCombos.size() / (catColSpan * categoryOptionSize);
                Collection<Integer> cols = new ArrayList<>(total);
                for (int i = 0; i < total; i++) {
                    cols.add(i);
                }
                colRepeat.put(cat.getId(), cols);
                catRepeat.put(cat.getId(), catColSpan);
            }
        }
        catColRepeat.put(categoryCombo.getId(), colRepeat);
    }
    // ---------------------------------------------------------------------
    // Get data entry form
    // ---------------------------------------------------------------------
    DataSet dsOriginal = dataSet;
    if (dataSet.getFormType().isDefault()) {
        DataSet dataSetCopy = new DataSet();
        dataSetCopy.setUid(dataSet.getUid());
        dataSetCopy.setCode(dataSet.getCode());
        dataSetCopy.setName(dataSet.getName());
        dataSetCopy.setShortName(dataSet.getShortName());
        dataSetCopy.setRenderAsTabs(dataSet.isRenderAsTabs());
        dataSetCopy.setRenderHorizontally(dataSet.isRenderHorizontally());
        dataSetCopy.setDataElementDecoration(dataSet.isDataElementDecoration());
        dataSetCopy.setCompulsoryDataElementOperands(dataSet.getCompulsoryDataElementOperands());
        for (int i = 0; i < orderedCategoryCombos.size(); i++) {
            CategoryCombo categoryCombo = orderedCategoryCombos.get(i);
            String name = !categoryCombo.isDefault() ? categoryCombo.getName() : dataSetCopy.getName();
            Section section = new Section();
            section.setUid(CodeGenerator.generateUid());
            section.setId(i);
            section.setName(name);
            section.setSortOrder(i);
            section.setDataSet(dataSetCopy);
            dataSetCopy.getSections().add(section);
            section.getDataElements().addAll(orderedDataElements.get(categoryCombo));
            if (i == 0) {
                section.setIndicators(new ArrayList<>(dataSet.getIndicators()));
            }
        }
        dataSet = dataSetCopy;
        formType = FormType.SECTION;
    }
    if (CodeGenerator.isValidUid(multiOrganisationUnit)) {
        OrganisationUnit organisationUnit = organisationUnitService.getOrganisationUnit(multiOrganisationUnit);
        List<OrganisationUnit> organisationUnitChildren = new ArrayList<>();
        for (OrganisationUnit child : organisationUnit.getChildren()) {
            if (child.getDataSets().contains(dsOriginal)) {
                organisationUnitChildren.add(child);
            }
        }
        Collections.sort(organisationUnitChildren);
        organisationUnits.addAll(organisationUnitChildren);
        getSectionForm(dataSet);
        formType = FormType.SECTION_MULTIORG;
    }
    getSectionForm(dataSet);
    return formType.toString();
}
Also used : ListMap(org.hisp.dhis.common.ListMap) AggregateAccessManager(org.hisp.dhis.datavalue.AggregateAccessManager) SectionUtils(org.hisp.dhis.dxf2.util.SectionUtils) SectionOrderComparator(org.hisp.dhis.dataset.comparator.SectionOrderComparator) CategoryOption(org.hisp.dhis.category.CategoryOption) DataSet(org.hisp.dhis.dataset.DataSet) Autowired(org.springframework.beans.factory.annotation.Autowired) HashMap(java.util.HashMap) OrganisationUnitService(org.hisp.dhis.organisationunit.OrganisationUnitService) I18n(org.hisp.dhis.i18n.I18n) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) DataElement(org.hisp.dhis.dataelement.DataElement) CategoryComboSizeNameComparator(org.hisp.dhis.category.comparator.CategoryComboSizeNameComparator) Map(java.util.Map) User(org.hisp.dhis.user.User) DataElementOperand(org.hisp.dhis.dataelement.DataElementOperand) DataEntryForm(org.hisp.dhis.dataentryform.DataEntryForm) FormType(org.hisp.dhis.dataset.FormType) Collection(java.util.Collection) Set(java.util.Set) Category(org.hisp.dhis.category.Category) DataEntryFormService(org.hisp.dhis.dataentryform.DataEntryFormService) Collectors(java.util.stream.Collectors) Section(org.hisp.dhis.dataset.Section) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) List(java.util.List) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo) CurrentUserService(org.hisp.dhis.user.CurrentUserService) CategoryCombo(org.hisp.dhis.category.CategoryCombo) CodeGenerator(org.hisp.dhis.common.CodeGenerator) DataSetService(org.hisp.dhis.dataset.DataSetService) Action(com.opensymphony.xwork2.Action) Collections(java.util.Collections) User(org.hisp.dhis.user.User) Category(org.hisp.dhis.category.Category) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) DataSet(org.hisp.dhis.dataset.DataSet) ArrayList(java.util.ArrayList) DataElement(org.hisp.dhis.dataelement.DataElement) CategoryCombo(org.hisp.dhis.category.CategoryCombo) ArrayList(java.util.ArrayList) List(java.util.List) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) FormType(org.hisp.dhis.dataset.FormType) Section(org.hisp.dhis.dataset.Section) Collection(java.util.Collection) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo)

Example 28 with Category

use of org.hisp.dhis.category.Category in project dhis2-core by dhis2.

the class DefaultAdxDataService method getCatOptComboFromAttributes.

private CategoryOptionCombo getCatOptComboFromAttributes(Map<String, String> attributes, CategoryCombo catcombo, IdSchemes idSchemes) throws AdxException {
    CategoryComboMap catcomboMap;
    try {
        catcomboMap = new CategoryComboMap(catcombo, idSchemes.getCategoryOptionIdScheme());
    } catch (CategoryComboMapException ex) {
        log.info("Failed to create category combo map from: " + catcombo);
        throw new AdxException(ex.getMessage());
    }
    String compositeIdentifier = StringUtils.EMPTY;
    for (Category category : catcomboMap.getCategories()) {
        String categoryId = category.getPropertyValue(idSchemes.getCategoryIdScheme());
        if (categoryId == null) {
            throw new AdxException("No category " + idSchemes.getCategoryIdScheme().name() + " for: " + category.toString());
        }
        String catAttribute = attributes.get(categoryId);
        if (catAttribute == null) {
            throw new AdxException("Missing required attribute from category combo " + catcombo.getName() + ": " + categoryId);
        }
        compositeIdentifier += "\"" + catAttribute + "\"";
    }
    CategoryOptionCombo catOptionCombo = catcomboMap.getCategoryOptionCombo(compositeIdentifier);
    if (catOptionCombo == null) {
        throw new AdxException("Invalid attributes: " + attributes);
    }
    return catOptionCombo;
}
Also used : CategoryComboMap(org.hisp.dhis.category.CategoryComboMap) CategoryComboMapException(org.hisp.dhis.category.CategoryComboMap.CategoryComboMapException) Category(org.hisp.dhis.category.Category) CategoryOptionCombo(org.hisp.dhis.category.CategoryOptionCombo)

Example 29 with Category

use of org.hisp.dhis.category.Category in project dhis2-core by dhis2.

the class AdxDataSetMetadata method addExplodedCategoryAttributes.

private void addExplodedCategoryAttributes(CategoryOptionCombo coc, IdSchemes idSchemes) throws AdxException {
    Map<String, String> categoryAttributes = new HashMap<>();
    IdScheme cScheme = idSchemes.getCategoryIdScheme();
    IdScheme coScheme = idSchemes.getCategoryOptionIdScheme();
    if (!coc.isDefault()) {
        for (Category category : coc.getCategoryCombo().getCategories()) {
            String categoryId = category.getPropertyValue(cScheme);
            if (categoryId == null || !XMLChar.isValidName(categoryId)) {
                throw new AdxException("Category " + cScheme.name() + " for " + category.getName() + " is missing or invalid: " + categoryId);
            }
            String catOptId = category.getCategoryOption(coc).getPropertyValue(coScheme);
            if (catOptId == null || catOptId.isEmpty()) {
                throw new AdxException("CategoryOption " + coScheme.name() + " for " + category.getCategoryOption(coc).getName() + " is missing");
            }
            categoryAttributes.put(categoryId, catOptId);
        }
    }
    categoryOptionMap.put(coc.getId(), categoryAttributes);
}
Also used : Category(org.hisp.dhis.category.Category) HashMap(java.util.HashMap) IdScheme(org.hisp.dhis.common.IdScheme)

Example 30 with Category

use of org.hisp.dhis.category.Category in project dhis2-core by dhis2.

the class DefaultDataSetMetadataExportService method getDataSetMetadata.

// TODO add lock exceptions
// TODO add validation caching (ETag and If-None-Match).
@Override
public ObjectNode getDataSetMetadata() {
    User user = currentUserService.getCurrentUser();
    List<DataSet> dataSets = idObjectManager.getDataWriteAll(DataSet.class);
    Set<DataElement> dataElements = flatMapToSet(dataSets, DataSet::getDataElements);
    Set<Indicator> indicators = flatMapToSet(dataSets, DataSet::getIndicators);
    Set<CategoryCombo> dataElementCategoryCombos = flatMapToSet(dataElements, DataElement::getCategoryCombos);
    Set<CategoryCombo> dataSetCategoryCombos = mapToSet(dataSets, DataSet::getCategoryCombo);
    Set<Category> dataElementCategories = flatMapToSet(dataElementCategoryCombos, CategoryCombo::getCategories);
    Set<Category> dataSetCategories = flatMapToSet(dataSetCategoryCombos, CategoryCombo::getCategories);
    Set<CategoryOption> categoryOptions = getCategoryOptions(dataElementCategories, dataSetCategories, user);
    expressionService.substituteIndicatorExpressions(indicators);
    ObjectNode rootNode = fieldFilterService.createObjectNode();
    rootNode.putArray(DataSetSchemaDescriptor.PLURAL).addAll(asObjectNodes(dataSets, FIELDS_DATA_SETS, DataSet.class));
    rootNode.putArray(DataElementSchemaDescriptor.PLURAL).addAll(asObjectNodes(dataElements, FIELDS_DATA_ELEMENTS, DataElement.class));
    rootNode.putArray(IndicatorSchemaDescriptor.PLURAL).addAll(asObjectNodes(indicators, FIELDS_INDICATORS, Indicator.class));
    rootNode.putArray(CategoryComboSchemaDescriptor.PLURAL).addAll(asObjectNodes(dataElementCategoryCombos, FIELDS_DATAELEMENT_CAT_COMBOS, CategoryCombo.class)).addAll(asObjectNodes(dataSetCategoryCombos, FIELDS_DATA_SET_CAT_COMBOS, CategoryCombo.class));
    rootNode.putArray(CategorySchemaDescriptor.PLURAL).addAll(asObjectNodes(dataElementCategories, FIELDS_CATEGORIES, Category.class)).addAll(asObjectNodes(dataSetCategories, FIELDS_CATEGORIES, Category.class));
    rootNode.putArray(CategoryOptionSchemaDescriptor.PLURAL).addAll(asObjectNodes(categoryOptions, FIELDS_CATEGORIES, CategoryOption.class));
    return rootNode;
}
Also used : User(org.hisp.dhis.user.User) Category(org.hisp.dhis.category.Category) ObjectNode(com.fasterxml.jackson.databind.node.ObjectNode) DataSet(org.hisp.dhis.dataset.DataSet) Indicator(org.hisp.dhis.indicator.Indicator) DataElement(org.hisp.dhis.dataelement.DataElement) CategoryCombo(org.hisp.dhis.category.CategoryCombo) CategoryOption(org.hisp.dhis.category.CategoryOption)

Aggregations

Category (org.hisp.dhis.category.Category)61 CategoryOption (org.hisp.dhis.category.CategoryOption)25 CategoryCombo (org.hisp.dhis.category.CategoryCombo)22 Test (org.junit.jupiter.api.Test)21 CategoryOptionCombo (org.hisp.dhis.category.CategoryOptionCombo)13 CategoryOptionGroupSet (org.hisp.dhis.category.CategoryOptionGroupSet)13 ArrayList (java.util.ArrayList)12 User (org.hisp.dhis.user.User)12 DataElement (org.hisp.dhis.dataelement.DataElement)11 HashSet (java.util.HashSet)8 DataSet (org.hisp.dhis.dataset.DataSet)8 OrganisationUnitGroupSet (org.hisp.dhis.organisationunit.OrganisationUnitGroupSet)8 HashMap (java.util.HashMap)7 Date (java.util.Date)5 AnalyticsTableColumn (org.hisp.dhis.analytics.AnalyticsTableColumn)5 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)5 OrganisationUnitLevel (org.hisp.dhis.organisationunit.OrganisationUnitLevel)5 List (java.util.List)4 DataQueryParams (org.hisp.dhis.analytics.DataQueryParams)4 Attribute (org.hisp.dhis.attribute.Attribute)4