Search in sources :

Example 11 with CalculatedFieldType

use of org.activityinfo.model.type.expr.CalculatedFieldType in project activityinfo by bedatadriven.

the class SubFormAggregationTest method subFormAggregationTest.

@Test
public void subFormAggregationTest() {
    // Typical scenario with a household interview form
    // and a repeating househould member form
    FormClass siteForm = new FormClass(ResourceId.generateId());
    siteForm.setParentFormId(ResourceId.ROOT_ID);
    FormClass monthlyForm = new FormClass(ResourceId.generateId());
    monthlyForm.setParentFormId(siteForm.getId());
    monthlyForm.setSubFormKind(SubFormKind.MONTHLY);
    siteForm.setLabel("Household interview");
    FormField villageField = siteForm.addField().setLabel("Village Name").setType(TextType.SIMPLE);
    siteForm.addField().setLabel("Maximum Beneficiaries").setCode("BENE").setType(new CalculatedFieldType("MAX(HH)"));
    siteForm.addField().setLabel("Monthly Activities").setType(new SubFormReferenceType(monthlyForm.getId()));
    monthlyForm.setLabel("Monthly Activities");
    FormField countField = monthlyForm.addField().setLabel("Number of Beneficiaries").setCode("HH").setType(new QuantityType("households"));
    HrdStorageProvider catalog = new HrdStorageProvider();
    catalog.create(siteForm);
    catalog.create(monthlyForm);
    TypedRecordUpdate v1 = new TypedRecordUpdate();
    v1.setUserId(userId);
    v1.setRecordId(ResourceId.generateSubmissionId(siteForm));
    v1.set(villageField.getId(), TextValue.valueOf("Rutshuru"));
    TypedRecordUpdate v2 = new TypedRecordUpdate();
    v2.setUserId(userId);
    v2.setRecordId(ResourceId.generateSubmissionId(siteForm));
    v2.set(villageField.getId(), TextValue.valueOf("Beni"));
    TypedRecordUpdate month1 = new TypedRecordUpdate();
    month1.setUserId(userId);
    month1.setRecordId(ResourceId.generateSubmissionId(monthlyForm));
    month1.setParentId(v1.getRecordId());
    month1.set(countField.getId(), new Quantity(40));
    TypedRecordUpdate month2 = new TypedRecordUpdate();
    month2.setUserId(userId);
    month2.setRecordId(ResourceId.generateSubmissionId(monthlyForm));
    month2.setParentId(v1.getRecordId());
    month2.set(countField.getId(), new Quantity(30));
    TypedRecordUpdate month3 = new TypedRecordUpdate();
    month3.setUserId(userId);
    month3.setRecordId(ResourceId.generateSubmissionId(monthlyForm));
    month3.setParentId(v2.getRecordId());
    month3.set(countField.getId(), new Quantity(47));
    FormStorage siteCollection = catalog.getForm(siteForm.getId()).get();
    siteCollection.add(v1);
    siteCollection.add(v2);
    Optional<FormStorage> monthCollection = catalog.getForm(monthlyForm.getId());
    assertTrue(monthCollection.isPresent());
    monthCollection.get().add(month1);
    monthCollection.get().add(month2);
    monthCollection.get().add(month3);
    QueryModel queryModel = new QueryModel(siteForm.getId());
    queryModel.selectResourceId().as("id");
    queryModel.selectField("Village Name").as("village");
    queryModel.selectField("BENE").as("max_hh");
    ColumnSetBuilder builder = new ColumnSetBuilder(catalog, new NullFormSupervisor());
    ColumnSet columnSet = builder.build(queryModel);
    System.out.println(columnSet);
    assertThat(columnSet.getNumRows(), equalTo(2));
}
Also used : CalculatedFieldType(org.activityinfo.model.type.expr.CalculatedFieldType) Quantity(org.activityinfo.model.type.number.Quantity) ColumnSet(org.activityinfo.model.query.ColumnSet) QueryModel(org.activityinfo.model.query.QueryModel) TypedRecordUpdate(org.activityinfo.store.spi.TypedRecordUpdate) SubFormReferenceType(org.activityinfo.model.type.subform.SubFormReferenceType) ColumnSetBuilder(org.activityinfo.store.query.server.ColumnSetBuilder) FormStorage(org.activityinfo.store.spi.FormStorage) QuantityType(org.activityinfo.model.type.number.QuantityType) FormClass(org.activityinfo.model.form.FormClass) NullFormSupervisor(org.activityinfo.store.query.shared.NullFormSupervisor) FormField(org.activityinfo.model.form.FormField) Test(org.junit.Test)

Example 12 with CalculatedFieldType

use of org.activityinfo.model.type.expr.CalculatedFieldType in project activityinfo by bedatadriven.

the class CustomerCalcIndicatorTest method createFormClass.

private FormClass createFormClass() {
    SchemaDTO schema = execute(new GetSchema());
    UserDatabaseDTO db = schema.getDatabaseById(1);
    LocationTypeDTO locType = schema.getCountryById(1).getLocationTypes().get(0);
    ActivityFormDTO act = new ActivityFormDTO();
    act.setName("Calculated indicators");
    act.setLocationType(locType);
    act.setReportingFrequency(ActivityFormDTO.REPORT_ONCE);
    CreateResult createResult = execute(CreateEntity.Activity(db, act));
    ResourceId classId = activityFormClass(createResult.getNewId());
    FormClass formClass = assertResolves(locator.getFormClass(classId));
    FormField typeField = new FormField(ResourceId.generateFieldId(EnumType.TYPE_CLASS));
    typeField.setType(new EnumType(Cardinality.SINGLE, Arrays.asList(new EnumItem(EnumItem.generateId(), "Budgeted"), new EnumItem(EnumItem.generateId(), "Spent"))));
    typeField.setLabel("Typology");
    formClass.addElement(typeField);
    FormField expField = new FormField(quantityId());
    expField.setType(new QuantityType().setUnits("currency"));
    expField.setLabel("Expenditure");
    expField.setCode("EXP");
    FormField waterAllocField = new FormField(quantityId());
    waterAllocField.setType(new QuantityType().setUnits("%"));
    waterAllocField.setLabel("Allocation watter programme");
    waterAllocField.setCode("WATER_ALLOC");
    FormField pctInitialField = new FormField(quantityId());
    pctInitialField.setType(new QuantityType().setUnits("%"));
    pctInitialField.setLabel("Initial Cost - Not specified");
    pctInitialField.setCode("PCT_INITIAL");
    FormField pctInitialHardField = new FormField(quantityId());
    pctInitialHardField.setType(new QuantityType().setUnits("%"));
    pctInitialHardField.setLabel("Initial Cost - Cap Hard");
    pctInitialHardField.setCode("PCT_INITIAL_HARD");
    FormField pctInitialSoftField = new FormField(quantityId());
    pctInitialSoftField.setType(new QuantityType().setUnits("%"));
    pctInitialSoftField.setLabel("Initial Cost - Cap Soft");
    pctInitialSoftField.setCode("PCT_INITIAL_SOFT");
    FormField pctExtensionField = new FormField(quantityId());
    pctExtensionField.setType(new QuantityType().setUnits("%"));
    pctExtensionField.setLabel("Extension Cost - Not specified");
    pctExtensionField.setCode("PCT_EXTENSION");
    FormField pctExtensionHardField = new FormField(quantityId());
    pctExtensionHardField.setType(new QuantityType().setUnits("%"));
    pctExtensionHardField.setLabel("Extension Cost - Hard");
    pctExtensionHardField.setCode("PCT_EXTENSION_HARD");
    FormField pctExtensionSoftField = new FormField(quantityId());
    pctExtensionSoftField.setType(new QuantityType().setUnits("%"));
    pctExtensionSoftField.setLabel("Extension Cost - Soft");
    pctExtensionSoftField.setCode("PCT_EXTENSION_SOFT");
    FormField pctOpField = new FormField(quantityId());
    pctOpField.setType(new QuantityType().setUnits("%"));
    pctOpField.setLabel("Operational Cost");
    pctOpField.setCode("PCT_OP");
    FormField pctMaintenanceField = new FormField(quantityId());
    pctMaintenanceField.setType(new QuantityType().setUnits("%"));
    pctMaintenanceField.setLabel("Maintenance Cost");
    pctMaintenanceField.setCode("PCT_MAINTENANCE");
    FormField pctOpMaintField = new FormField(quantityId());
    pctOpMaintField.setType(new QuantityType().setUnits("%"));
    pctOpMaintField.setLabel("Operational & Maintenance Cost");
    pctOpMaintField.setCode("PCT_OP_MAINT");
    FormField waterExpField = new FormField(quantityId());
    waterExpField.setType(new QuantityType().setUnits("%"));
    waterExpField.setLabel("Expenditure on water programme");
    waterExpField.setCode("WATER_EXP");
    waterExpField.setType(new CalculatedFieldType("{EXP}*({WATER_ALLOC}/100)"));
    FormField initialField = new FormField(quantityId());
    initialField.setType(new QuantityType().setUnits("%"));
    initialField.setLabel("Value of Initial Cost - Not specified");
    initialField.setCode("INITIAL");
    initialField.setType(new CalculatedFieldType("{WATER_EXP}*({PCT_INITIAL}/100)"));
    FormField initialHardField = new FormField(quantityId());
    initialHardField.setType(new QuantityType().setUnits("%"));
    initialHardField.setLabel("Value of Initial Cost - Cap Hard");
    initialHardField.setCode("INITIAL_HARD");
    initialHardField.setType(new CalculatedFieldType("{WATER_EXP}*({PCT_INITIAL_HARD}/100)"));
    FormField initialSoftField = new FormField(quantityId());
    initialSoftField.setType(new QuantityType().setUnits("%"));
    initialSoftField.setLabel("Value of Initial Cost – Cap Soft");
    initialSoftField.setCode("INITIAL_SOFT");
    initialSoftField.setType(new CalculatedFieldType("{WATER_EXP}*({PCT_INITIAL_SOFT}/100)"));
    FormField initialTotalField = new FormField(quantityId());
    initialTotalField.setType(new QuantityType().setUnits("%"));
    initialTotalField.setLabel("Total Value of Initial Cost");
    initialTotalField.setCode("INITIAL_TOTAL");
    initialTotalField.setType(new CalculatedFieldType("{INITIAL}+{INITIAL_HARD}+{INITIAL_SOFT}"));
    formClass.addElement(expField);
    formClass.addElement(waterAllocField);
    formClass.addElement(pctInitialField);
    formClass.addElement(pctInitialHardField);
    formClass.addElement(pctInitialSoftField);
    formClass.addElement(pctExtensionField);
    formClass.addElement(pctExtensionHardField);
    formClass.addElement(pctExtensionSoftField);
    formClass.addElement(pctOpField);
    formClass.addElement(pctMaintenanceField);
    formClass.addElement(pctOpMaintField);
    formClass.addElement(waterExpField);
    formClass.addElement(initialField);
    formClass.addElement(initialHardField);
    formClass.addElement(initialSoftField);
    formClass.addElement(initialTotalField);
    assertResolves(locator.persist(formClass));
    FormClass reform = assertResolves(locator.getFormClass(formClass.getId()));
    assertHasFieldWithLabel(reform, "Expenditure");
    assertHasFieldWithLabel(reform, "Allocation watter programme");
    assertHasFieldWithLabel(reform, "Initial Cost - Not specified");
    assertHasFieldWithLabel(reform, "Initial Cost - Cap Hard");
    assertHasFieldWithLabel(reform, "Initial Cost - Cap Soft");
    assertHasFieldWithLabel(reform, "Extension Cost - Not specified");
    assertHasFieldWithLabel(reform, "Extension Cost - Hard");
    assertHasFieldWithLabel(reform, "Extension Cost - Soft");
    assertHasFieldWithLabel(reform, "Operational Cost");
    assertHasFieldWithLabel(reform, "Maintenance Cost");
    assertHasFieldWithLabel(reform, "Operational & Maintenance Cost");
    assertHasFieldWithLabel(reform, "Expenditure on water programme");
    assertHasFieldWithLabel(reform, "Value of Initial Cost - Not specified");
    assertHasFieldWithLabel(reform, "Value of Initial Cost - Cap Hard");
    assertHasFieldWithLabel(reform, "Value of Initial Cost – Cap Soft");
    assertHasFieldWithLabel(reform, "Total Value of Initial Cost");
    return reform;
}
Also used : CalculatedFieldType(org.activityinfo.model.type.expr.CalculatedFieldType) CreateResult(org.activityinfo.legacy.shared.command.result.CreateResult) ResourceId(org.activityinfo.model.resource.ResourceId) QuantityType(org.activityinfo.model.type.number.QuantityType) FormClass(org.activityinfo.model.form.FormClass) CuidAdapter.activityFormClass(org.activityinfo.model.legacy.CuidAdapter.activityFormClass) EnumType(org.activityinfo.model.type.enumerated.EnumType) EnumItem(org.activityinfo.model.type.enumerated.EnumItem) FormField(org.activityinfo.model.form.FormField)

Example 13 with CalculatedFieldType

use of org.activityinfo.model.type.expr.CalculatedFieldType in project activityinfo by bedatadriven.

the class QueryEvaluatorTest method circularReference.

@Test
public void circularReference() throws Exception {
    final FormClass formClass = new FormClass(ResourceId.valueOf("XYZ"));
    formClass.addField(ResourceId.valueOf("FA")).setCode("A").setLabel("Field A").setType(new CalculatedFieldType("B"));
    formClass.addField(ResourceId.valueOf("FB")).setCode("B").setLabel("Field B").setType(new CalculatedFieldType("A"));
    FormStorageProviderStub catalog = new FormStorageProviderStub();
    catalog.addForm(formClass).withRowCount(10);
    ColumnSetBuilder builder = new ColumnSetBuilder(catalog, new NullFormScanCache(), new NullFormSupervisor());
    FormScanBatch batch = builder.createNewBatch();
    QueryEvaluator evaluator = new QueryEvaluator(FilterLevel.BASE, catalog.getTree(formClass.getId()), batch);
    Slot<ColumnView> a = evaluator.evaluateExpression(new SymbolNode("A"));
    Slot<ColumnView> aPlusOne = evaluator.evaluateExpression(FormulaParser.parse("A+1"));
    builder.execute(batch);
    assertThat(a.get().numRows(), equalTo(10));
    assertThat(a.get().getString(0), nullValue());
    assertThat(aPlusOne.get().getString(0), nullValue());
    assertThat(aPlusOne.get().getDouble(0), equalTo(1d));
}
Also used : ColumnSetBuilder(org.activityinfo.store.query.server.ColumnSetBuilder) SymbolNode(org.activityinfo.model.formula.SymbolNode) CalculatedFieldType(org.activityinfo.model.type.expr.CalculatedFieldType) FormClass(org.activityinfo.model.form.FormClass) ColumnView(org.activityinfo.model.query.ColumnView) Test(org.junit.Test)

Example 14 with CalculatedFieldType

use of org.activityinfo.model.type.expr.CalculatedFieldType in project activityinfo by bedatadriven.

the class PivotAdapter method selectedIndicators.

private List<ActivityField> selectedIndicators(Activity activity) {
    if (filter.isRestricted(DimensionType.Activity)) {
        if (!filter.getRestrictions(DimensionType.Activity).contains(activity.getId())) {
            return Collections.emptyList();
        }
    }
    if (filter.isRestricted(DimensionType.Database)) {
        if (!filter.getRestrictions(DimensionType.Database).contains(activity.getDatabaseId())) {
            return Collections.emptyList();
        }
    }
    List<ActivityField> matching = Lists.newArrayList();
    Set<Integer> restrictedIndicatorIds = filter.getRestrictions(DimensionType.Indicator);
    for (ActivityField field : activity.getIndicatorFields()) {
        FieldType type = field.getFormField().getType();
        if (type instanceof QuantityType || type instanceof CalculatedFieldType) {
            if (restrictedIndicatorIds.isEmpty() || restrictedIndicatorIds.contains(field.getId())) {
                matching.add(field);
            }
        }
    }
    return matching;
}
Also used : CalculatedFieldType(org.activityinfo.model.type.expr.CalculatedFieldType) QuantityType(org.activityinfo.model.type.number.QuantityType) ActivityField(org.activityinfo.store.mysql.metadata.ActivityField) FieldType(org.activityinfo.model.type.FieldType) CalculatedFieldType(org.activityinfo.model.type.expr.CalculatedFieldType)

Example 15 with CalculatedFieldType

use of org.activityinfo.model.type.expr.CalculatedFieldType in project activityinfo by bedatadriven.

the class MySqlUpdateTest method createFormWithCalculationAndRelevance.

@Test
public void createFormWithCalculationAndRelevance() {
    userId = 1;
    KeyGenerator generator = new KeyGenerator();
    int activityId = generator.generateInt();
    FormClass formClass = new FormClass(CuidAdapter.activityFormClass(activityId));
    formClass.setDatabaseId(1);
    formClass.setLabel("New Form");
    FormField numberField = new FormField(CuidAdapter.generateIndicatorId()).setType(new QuantityType("widgets")).setLabel("NUM").setRequired(true);
    formClass.addElement(numberField);
    FormField calculatedField = new FormField(CuidAdapter.generateIndicatorId()).setType(new CalculatedFieldType("1")).setLabel("Calculation").setRelevanceConditionExpression("NUM>42").setRequired(true);
    formClass.addElement(calculatedField);
    catalog.createOrUpdateFormSchema(formClass);
    newRequest();
    // Create two records
    RecordTransactionBuilder tx = new RecordTransactionBuilder();
    RecordUpdate site1 = tx.update(formClass.getId(), CuidAdapter.generateSiteCuid());
    site1.setFieldValue(numberField.getId(), new Quantity(10));
    site1.setFieldValue(partnerField(activityId), CuidAdapter.partnerRef(1, 1));
    RecordUpdate site2 = tx.update(formClass.getId(), CuidAdapter.generateSiteCuid());
    site2.setFieldValue(numberField.getId(), new Quantity(60));
    site2.setFieldValue(partnerField(activityId), CuidAdapter.partnerRef(1, 1));
    updater().execute(tx.build());
    newRequest();
    // Query results
    QueryModel queryModel = new QueryModel(formClass.getId());
    queryModel.selectResourceId();
    queryModel.selectExpr("Num").as("num");
    queryModel.selectExpr("Calculation").as("calc");
    query(queryModel);
    ColumnView num = columnSet.getColumnView("num");
    ColumnView calculation = columnSet.getColumnView("calc");
    assertThat(calculation.isMissing(0), equalTo(num.getDouble(0) <= 42));
    assertThat(calculation.isMissing(1), equalTo(num.getDouble(1) <= 42));
}
Also used : RecordTransactionBuilder(org.activityinfo.model.resource.RecordTransactionBuilder) CalculatedFieldType(org.activityinfo.model.type.expr.CalculatedFieldType) RecordUpdate(org.activityinfo.model.resource.RecordUpdate) TypedRecordUpdate(org.activityinfo.store.spi.TypedRecordUpdate) QuantityType(org.activityinfo.model.type.number.QuantityType) FormClass(org.activityinfo.model.form.FormClass) ColumnView(org.activityinfo.model.query.ColumnView) Quantity(org.activityinfo.model.type.number.Quantity) KeyGenerator(org.activityinfo.model.legacy.KeyGenerator) FormField(org.activityinfo.model.form.FormField) QueryModel(org.activityinfo.model.query.QueryModel) GeoPoint(org.activityinfo.model.type.geo.GeoPoint) Test(org.junit.Test)

Aggregations

CalculatedFieldType (org.activityinfo.model.type.expr.CalculatedFieldType)16 QuantityType (org.activityinfo.model.type.number.QuantityType)12 FormClass (org.activityinfo.model.form.FormClass)7 FormField (org.activityinfo.model.form.FormField)7 Test (org.junit.Test)6 EnumType (org.activityinfo.model.type.enumerated.EnumType)4 FieldType (org.activityinfo.model.type.FieldType)3 ColumnView (org.activityinfo.model.query.ColumnView)2 QueryModel (org.activityinfo.model.query.QueryModel)2 ResourceId (org.activityinfo.model.resource.ResourceId)2 NarrativeType (org.activityinfo.model.type.NarrativeType)2 ReferenceType (org.activityinfo.model.type.ReferenceType)2 EnumItem (org.activityinfo.model.type.enumerated.EnumItem)2 Quantity (org.activityinfo.model.type.number.Quantity)2 TextType (org.activityinfo.model.type.primitive.TextType)2 SubFormReferenceType (org.activityinfo.model.type.subform.SubFormReferenceType)2 LocalDateType (org.activityinfo.model.type.time.LocalDateType)2 ColumnSetBuilder (org.activityinfo.store.query.server.ColumnSetBuilder)2 TypedRecordUpdate (org.activityinfo.store.spi.TypedRecordUpdate)2 SqlResultCallback (com.bedatadriven.rebar.sql.client.SqlResultCallback)1