Search in sources :

Example 16 with DataValue

use of org.hisp.dhis.datavalue.DataValue in project dhis2-core by dhis2.

the class DhisConvenienceTest method createDataValue.

/**
     * @param dataElement          The data element.
     * @param period               The period.
     * @param source               The source.
     * @param value                The value.
     * @param categoryOptionCombo  The category option combo.
     * @param attributeOptionCombo The attribute option combo.
     */
public static DataValue createDataValue(DataElement dataElement, Period period, OrganisationUnit source, String value, DataElementCategoryOptionCombo categoryOptionCombo, DataElementCategoryOptionCombo attributeOptionCombo) {
    DataValue dataValue = new DataValue();
    dataValue.setDataElement(dataElement);
    dataValue.setPeriod(period);
    dataValue.setSource(source);
    dataValue.setCategoryOptionCombo(categoryOptionCombo);
    dataValue.setAttributeOptionCombo(attributeOptionCombo);
    dataValue.setValue(value);
    dataValue.setComment("Comment");
    dataValue.setStoredBy("StoredBy");
    return dataValue;
}
Also used : DataValue(org.hisp.dhis.datavalue.DataValue)

Example 17 with DataValue

use of org.hisp.dhis.datavalue.DataValue in project dhis2-core by dhis2.

the class DataValueController method saveDataValue.

// ---------------------------------------------------------------------
// POST
// ---------------------------------------------------------------------
@PreAuthorize("hasRole('ALL') or hasRole('F_DATAVALUE_ADD')")
@RequestMapping(method = RequestMethod.POST)
@ResponseStatus(HttpStatus.CREATED)
public void saveDataValue(@RequestParam String de, @RequestParam(required = false) String co, @RequestParam(required = false) String cc, @RequestParam(required = false) String cp, @RequestParam String pe, @RequestParam String ou, @RequestParam(required = false) String value, @RequestParam(required = false) String comment, @RequestParam(required = false) boolean followUp, HttpServletResponse response) throws WebMessageException {
    boolean strictPeriods = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_PERIODS);
    boolean strictCategoryOptionCombos = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_CATEGORY_OPTION_COMBOS);
    boolean strictOrgUnits = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_STRICT_ORGANISATION_UNITS);
    boolean requireCategoryOptionCombo = (Boolean) systemSettingManager.getSystemSetting(SettingKey.DATA_IMPORT_REQUIRE_CATEGORY_OPTION_COMBO);
    // ---------------------------------------------------------------------
    // Input validation
    // ---------------------------------------------------------------------
    DataElement dataElement = getAndValidateDataElement(de);
    DataElementCategoryOptionCombo categoryOptionCombo = getAndValidateCategoryOptionCombo(co, requireCategoryOptionCombo);
    DataElementCategoryOptionCombo attributeOptionCombo = getAndValidateAttributeOptionCombo(cc, cp);
    Period period = getAndValidatePeriod(pe);
    OrganisationUnit organisationUnit = getAndValidateOrganisationUnit(ou);
    validateInvalidFuturePeriod(period, dataElement);
    validateAttributeOptionComboWithOrgUnitAndPeriod(attributeOptionCombo, organisationUnit, period);
    String valueValid = ValidationUtils.dataValueIsValid(value, dataElement);
    if (valueValid != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Invalid value: " + value + ", must match data element type: " + dataElement.getValueType()));
    }
    String commentValid = ValidationUtils.commentIsValid(comment);
    if (commentValid != null) {
        throw new WebMessageException(WebMessageUtils.conflict("Invalid comment: " + comment));
    }
    OptionSet optionSet = dataElement.getOptionSet();
    if (!Strings.isNullOrEmpty(value) && optionSet != null && !optionSet.getOptionCodesAsSet().contains(value)) {
        throw new WebMessageException(WebMessageUtils.conflict("Data value is not a valid option of the data element option set: " + dataElement.getUid()));
    }
    if (strictPeriods && !dataElement.getPeriodTypes().contains(period.getPeriodType())) {
        throw new WebMessageException(WebMessageUtils.conflict("Period type of period: " + period.getIsoDate() + " not valid for data element: " + dataElement.getUid()));
    }
    if (strictCategoryOptionCombos && !dataElement.getCategoryOptionCombos().contains(categoryOptionCombo)) {
        throw new WebMessageException(WebMessageUtils.conflict("Category option combo: " + categoryOptionCombo.getUid() + " must be part of category combo of data element: " + dataElement.getUid()));
    }
    if (strictOrgUnits && !organisationUnit.hasDataElement(dataElement)) {
        throw new WebMessageException(WebMessageUtils.conflict("Data element: " + dataElement.getUid() + " must be assigned through data sets to organisation unit: " + organisationUnit.getUid()));
    }
    // ---------------------------------------------------------------------
    // Locking validation
    // ---------------------------------------------------------------------
    validateDataSetNotLocked(dataElement, period, organisationUnit, attributeOptionCombo);
    // ---------------------------------------------------------------------
    // Period validation
    // ---------------------------------------------------------------------
    validateDataInputPeriodForDataElementAndPeriod(dataElement, period);
    // ---------------------------------------------------------------------
    // Assemble and save data value
    // ---------------------------------------------------------------------
    String storedBy = currentUserService.getCurrentUsername();
    Date now = new Date();
    DataValue dataValue = dataValueService.getDataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo);
    FileResource fileResource = null;
    if (dataValue == null) {
        if (dataElement.getValueType() == ValueType.FILE_RESOURCE) {
            if (value != null) {
                fileResource = fileResourceService.getFileResource(value);
                if (fileResource == null || fileResource.getDomain() != FileResourceDomain.DATA_VALUE) {
                    throw new WebMessageException(WebMessageUtils.notFound(FileResource.class, value));
                }
                if (fileResource.isAssigned()) {
                    throw new WebMessageException(WebMessageUtils.conflict("File resource already assigned or linked to another data value"));
                }
                fileResource.setAssigned(true);
            } else {
                throw new WebMessageException(WebMessageUtils.conflict("Missing parameter 'value'"));
            }
        }
        dataValue = new DataValue(dataElement, period, organisationUnit, categoryOptionCombo, attributeOptionCombo, StringUtils.trimToNull(value), storedBy, now, StringUtils.trimToNull(comment));
        dataValueService.addDataValue(dataValue);
    } else {
        if (value == null && ValueType.TRUE_ONLY.equals(dataElement.getValueType())) {
            if (comment == null) {
                dataValueService.deleteDataValue(dataValue);
                return;
            } else {
                value = "false";
            }
        }
        if (dataElement.isFileType()) {
            fileResourceService.deleteFileResource(dataValue.getValue());
        }
        if (value != null) {
            dataValue.setValue(StringUtils.trimToNull(value));
        }
        if (comment != null) {
            dataValue.setComment(StringUtils.trimToNull(comment));
        }
        if (followUp) {
            dataValue.toggleFollowUp();
        }
        dataValue.setLastUpdated(now);
        dataValue.setStoredBy(storedBy);
        dataValueService.updateDataValue(dataValue);
    }
    if (fileResource != null) {
        fileResourceService.updateFileResource(fileResource);
    }
}
Also used : DataElement(org.hisp.dhis.dataelement.DataElement) OrganisationUnit(org.hisp.dhis.organisationunit.OrganisationUnit) WebMessageException(org.hisp.dhis.dxf2.webmessage.WebMessageException) DataValue(org.hisp.dhis.datavalue.DataValue) FileResource(org.hisp.dhis.fileresource.FileResource) Period(org.hisp.dhis.period.Period) OptionSet(org.hisp.dhis.option.OptionSet) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo) Date(java.util.Date) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus) PreAuthorize(org.springframework.security.access.prepost.PreAuthorize) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 18 with DataValue

use of org.hisp.dhis.datavalue.DataValue in project dhis2-core by dhis2.

the class DefaultPredictorService method writeDataValue.

/**
     * Writes (adds or updates) a predicted data value to the database.
     *
     * @param dataElement the data element.
     * @param period the period.
     * @param orgUnit the organisation unit.
     * @param categoryOptionCombo the category option combo.
     * @param attributeOptionCombo the attribute option combo.
     * @param value the value.
     * @param storedBy the user that will store this data value.
     */
private void writeDataValue(DataElement dataElement, Period period, OrganisationUnit orgUnit, DataElementCategoryOptionCombo categoryOptionCombo, DataElementCategoryOptionCombo attributeOptionCombo, String value, String storedBy) {
    DataValue existingValue = dataValueService.getDataValue(dataElement, period, orgUnit, categoryOptionCombo, attributeOptionCombo);
    if (existingValue != null) {
        existingValue.setValue(value);
        existingValue.setStoredBy(storedBy);
        dataValueService.updateDataValue(existingValue);
    } else {
        DataValue dv = new DataValue(dataElement, period, orgUnit, categoryOptionCombo, attributeOptionCombo, value, storedBy, null, null);
        dataValueService.addDataValue(dv);
    }
}
Also used : DataValue(org.hisp.dhis.datavalue.DataValue)

Example 19 with DataValue

use of org.hisp.dhis.datavalue.DataValue in project dhis2-core by dhis2.

the class DataValueSMSListener method storeDataValue.

private boolean storeDataValue(String sender, OrganisationUnit orgunit, Map<String, String> parsedMessage, SMSCode code, SMSCommand command, Date date, DataSet dataSet) {
    String storedBy = SmsUtils.getUser(sender, command, userService.getUsersByPhoneNumber(sender)).getUsername();
    if (StringUtils.isBlank(storedBy)) {
        storedBy = "[unknown] from [" + sender + "]";
    }
    DataElementCategoryOptionCombo optionCombo = dataElementCategoryService.getDataElementCategoryOptionCombo(code.getOptionId());
    Period period = getPeriod(command, date);
    DataValue dv = dataValueService.getDataValue(code.getDataElement(), period, orgunit, optionCombo);
    String value = parsedMessage.get(code.getCode());
    Set<SMSSpecialCharacter> specialCharacters = command.getSpecialCharacters();
    for (SMSSpecialCharacter each : specialCharacters) {
        if (each.getName().equalsIgnoreCase(value)) {
            value = each.getValue();
            break;
        }
    }
    if (!StringUtils.isEmpty(value)) {
        boolean newDataValue = false;
        if (dv == null) {
            dv = new DataValue();
            dv.setCategoryOptionCombo(optionCombo);
            dv.setSource(orgunit);
            dv.setDataElement(code.getDataElement());
            dv.setPeriod(period);
            dv.setComment("");
            newDataValue = true;
        }
        if (ValueType.BOOLEAN == dv.getDataElement().getValueType()) {
            if ("Y".equals(value.toUpperCase()) || "YES".equals(value.toUpperCase())) {
                value = "true";
            } else if ("N".equals(value.toUpperCase()) || "NO".equals(value.toUpperCase())) {
                value = "false";
            }
        } else if (dv.getDataElement().getValueType().isInteger()) {
            try {
                Integer.parseInt(value);
            } catch (NumberFormatException e) {
                return false;
            }
        }
        dv.setValue(value);
        dv.setLastUpdated(new java.util.Date());
        dv.setStoredBy(storedBy);
        if (newDataValue) {
            dataValueService.addDataValue(dv);
        } else {
            dataValueService.updateDataValue(dv);
        }
    }
    if (code.getFormula() != null) {
        try {
            String formula = code.getFormula();
            String targetDataElementId = formula.substring(1, formula.length());
            String operation = String.valueOf(formula.charAt(0));
            DataElement targetDataElement = dataElementService.getDataElement(Integer.parseInt(targetDataElementId));
            if (targetDataElement == null) {
                return false;
            }
            DataValue targetDataValue = dataValueService.getDataValue(targetDataElement, period, orgunit, dataElementCategoryService.getDefaultDataElementCategoryOptionCombo());
            int targetValue = 0;
            boolean newTargetDataValue = false;
            if (targetDataValue == null) {
                targetDataValue = new DataValue();
                targetDataValue.setCategoryOptionCombo(dataElementCategoryService.getDefaultDataElementCategoryOptionCombo());
                targetDataValue.setSource(orgunit);
                targetDataValue.setDataElement(targetDataElement);
                targetDataValue.setPeriod(period);
                targetDataValue.setComment("");
                newTargetDataValue = true;
            } else {
                targetValue = Integer.parseInt(targetDataValue.getValue());
            }
            if (operation.equals("+")) {
                targetValue = targetValue + Integer.parseInt(value);
            } else if (operation.equals("-")) {
                targetValue = targetValue - Integer.parseInt(value);
            }
            targetDataValue.setValue(String.valueOf(targetValue));
            targetDataValue.setLastUpdated(new java.util.Date());
            targetDataValue.setStoredBy(storedBy);
            if (newTargetDataValue) {
                dataValueService.addDataValue(targetDataValue);
            } else {
                dataValueService.updateDataValue(targetDataValue);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}
Also used : DataValue(org.hisp.dhis.datavalue.DataValue) Date(java.util.Date) Period(org.hisp.dhis.period.Period) SMSParserException(org.hisp.dhis.sms.parse.SMSParserException) DataElement(org.hisp.dhis.dataelement.DataElement) SMSSpecialCharacter(org.hisp.dhis.sms.command.SMSSpecialCharacter) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)

Example 20 with DataValue

use of org.hisp.dhis.datavalue.DataValue in project dhis2-core by dhis2.

the class J2MEDataValueSMSListener method sendSuccessFeedback.

private void sendSuccessFeedback(String sender, SMSCommand command, Map<String, String> parsedMessage, Period period, OrganisationUnit orgunit) {
    String reportBack = "Thank you! Values entered: ";
    String notInReport = "Missing values for: ";
    boolean missingElements = false;
    for (SMSCode code : command.getCodes()) {
        DataElementCategoryOptionCombo optionCombo = dataElementCategoryService.getDataElementCategoryOptionCombo(code.getOptionId());
        DataValue dv = dataValueService.getDataValue(code.getDataElement(), period, orgunit, optionCombo);
        if (dv == null && !StringUtils.isEmpty(code.getCode())) {
            notInReport += code.getCode() + ",";
            missingElements = true;
        } else if (dv != null) {
            String value = dv.getValue();
            if (ValueType.BOOLEAN == dv.getDataElement().getValueType()) {
                if ("true".equals(value)) {
                    value = "Yes";
                } else if ("false".equals(value)) {
                    value = "No";
                }
            }
            reportBack += code.getCode() + "=" + value + " ";
        }
    }
    notInReport = notInReport.substring(0, notInReport.length() - 1);
    if (missingElements) {
        reportBack += notInReport;
    }
    if (command.getSuccessMessage() != null && !StringUtils.isEmpty(command.getSuccessMessage())) {
        reportBack = command.getSuccessMessage();
    }
    smsSender.sendMessage(null, reportBack, sender);
}
Also used : DataValue(org.hisp.dhis.datavalue.DataValue) SMSCode(org.hisp.dhis.sms.command.code.SMSCode) DataElementCategoryOptionCombo(org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)

Aggregations

DataValue (org.hisp.dhis.datavalue.DataValue)49 DataElementCategoryOptionCombo (org.hisp.dhis.dataelement.DataElementCategoryOptionCombo)20 Period (org.hisp.dhis.period.Period)19 Test (org.junit.Test)19 DhisSpringTest (org.hisp.dhis.DhisSpringTest)18 ImportSummary (org.hisp.dhis.dxf2.importsummary.ImportSummary)18 ClassPathResource (org.springframework.core.io.ClassPathResource)16 DataElement (org.hisp.dhis.dataelement.DataElement)15 OrganisationUnit (org.hisp.dhis.organisationunit.OrganisationUnit)11 Date (java.util.Date)7 ArrayList (java.util.ArrayList)4 CompleteDataSetRegistration (org.hisp.dhis.dataset.CompleteDataSetRegistration)4 DataValueAudit (org.hisp.dhis.datavalue.DataValueAudit)4 WebMessageException (org.hisp.dhis.dxf2.webmessage.WebMessageException)4 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)4 DataElementOperand (org.hisp.dhis.dataelement.DataElementOperand)3 DataSet (org.hisp.dhis.dataset.DataSet)3 DataExportParams (org.hisp.dhis.datavalue.DataExportParams)3 ImportOptions (org.hisp.dhis.dxf2.common.ImportOptions)3 SMSCode (org.hisp.dhis.sms.command.code.SMSCode)3