Blog

Groovy business rule examples for Planning (PBCS): a practical cookbook

Calc scripts are still the workhorse of Planning (formerly PBCS). Groovy rules earn their place when a calculation needs to know something a calc script can't: which cells the user just changed, whether the input makes sense, or which members to calculate based on data. This cookbook collects the patterns that come up on almost every implementation, with code you can adapt.

Everything below runs as a Groovy business rule created in Calculation Manager and attached to a form or launched from the rules list. Test every rule in a test environment first. The application, cube and member names (OEP_FS, SHARED_SVCS and so on) are examples; replace them with your own.

How a Groovy rule runs

A few facts explain most of the patterns:

  • When a rule runs from a form, operation.grid gives you the form's data grid, including which cells were edited.
  • A Groovy rule can return a calc script as a string. Planning then runs that calc script against the cube. This is the most common pattern: Groovy decides what to calculate, the calc script does the calculating.
  • Runtime prompts are declared in a comment on the first line, /*RTPS: {Entity} {Scenario}*/, and read through rtps.
  • println writes to the job's log, which you can read in the job console. Use it freely while developing.

1. Calculate only what the user changed

The classic performance win. Instead of calculating every entity on the form, collect the edited intersections and calculate only those.

// Collect the entities the user edited on the form
Set<String> entities = []
operation.grid.dataCellIterator({ DataCell cell -> cell.edited }).each { DataCell cell ->
    entities << cell.getMemberName("Entity")
}

if (entities.isEmpty()) {
    println "No edited cells, nothing to calculate"
    return
}

String entityList = entities.collect { "\"$it\"" }.join(", ")

"""
FIX($entityList, "Forecast", "Working", @RELATIVE("YearTotal", 0))
    "Gross_Margin" = "Revenue" - "Cost_of_Sales";
ENDFIX
""".toString()

Attach the rule to the form so it runs on save. On a form with fifty entities where the user changed two, this calculates two. Collect any other dimension the same way (accounts, periods, products) when the calculation can be narrowed further.

2. Validate input and stop the save

Run this before save. If any edited cell breaks a rule, the save is refused and the user sees the message.

def messages = messageBundle([
    "validation.negativeHeadcount": "Headcount can't be negative (entity {0}, {1})."
])
def loader = messageBundleLoader(["en": messages])

operation.grid.dataCellIterator({ DataCell cell -> cell.edited }).each { DataCell cell ->
    if (cell.getMemberName("Account") == "Headcount" && !cell.missing && cell.data < 0) {
        throwVetoException(loader, "validation.negativeHeadcount",
            cell.getMemberName("Entity"), cell.periodName)
    }
}

Keep validation messages specific: name the member and the period, and say what a valid value looks like. To mark cells without refusing the save, cell.addValidationError(0xFF0000, "message") highlights the cell and shows the message to the user instead.

3. Read data with a grid definition

When the logic depends on data that isn't on the form, load it yourself. The flexible builder accepts member functions, so you don't have to list members.

Cube cube = operation.application.getCube("OEP_FS")

FlexibleDataGridDefinitionBuilder builder = cube.flexibleDataGridDefinitionBuilder()
builder.setPov(["Years", "Scenario", "Version", "Currency", "Product"],
               [["FY27"], ["Forecast"], ["Working"], ["USD"], ["No Product"]])
builder.addColumn(["Period"], [['ILvl0Descendants("YearTotal")']])
builder.addRow(["Entity", "Account"], [['ILvl0Descendants("SHARED_SVCS")'], ["Headcount"]])

cube.loadGrid(builder.build(), false).withCloseable { DataGrid grid ->
    grid.dataCellIterator().each { DataCell cell ->
        if (!cell.missing) {
            println "${cell.getMemberName("Entity")} ${cell.periodName}: ${cell.formattedValue}"
        }
    }
}

Every dimension of the cube must be on the POV, rows or columns. Close grids when you're done; withCloseable does it for you, even when the code throws.

4. Write data with DataGridBuilder

To write values computed in Groovy, build a grid and save it. The status object tells you how many cells were accepted.

Cube cube = operation.application.getCube("OEP_FS")

DataGridBuilder builder = cube.dataGridBuilder("MM/DD/YYYY")
builder.addPov("FY27", "Forecast", "Working", "USD", "No Product")
builder.addColumn("Jan", "Feb", "Mar")
builder.addRow(["CC4100", "Facilities_Alloc"], [1200, 1200, 1250])
builder.addRow(["CC4110", "Facilities_Alloc"], [800, 800, 820])

DataGridBuilder.Status status = new DataGridBuilder.Status()
builder.build(status).withCloseable { DataGrid grid ->
    println "Accepted ${status.numAcceptedCells}, rejected ${status.numRejectedCells}"
    if (status.numRejectedCells > 0) {
        println "Rejected cells: ${status.cellsRejected}"
    }
    cube.saveGrid(grid)
}

The POV members are given in dimension order, and together with the row and column members they must make a full intersection. Rejected cells usually mean a member name is wrong or the intersection isn't valid for that cube, so log them rather than letting them disappear.

5. Run a focused calc script from runtime prompts

A rule launched from the rules list or a form menu can take runtime prompts and build its calc script from them.

/*RTPS: {Entity} {Scenario}*/
String entity = rtps.Entity.member.name
String scenario = rtps.Scenario.member.name

"""
FIX(@RELATIVE("$entity", 0), "$scenario", "Working")
    AGG("Product");
ENDFIX
""".toString()

Building the script in Groovy also lets you check the prompt values first, for example refusing to run on an upper level, or on a scenario that's locked for the period, with a clear message instead of a calc script error.

6. Push the changed data to a reporting cube

After a calculation, users often expect to see the result in a reporting (ASO) cube right away. Smart Push sends just the form's slice; a data map moves a larger, fixed region.

// Push only the entities edited on this form, using the form's Smart Push definition
Set<String> entities = []
operation.grid.dataCellIterator({ DataCell cell -> cell.edited }).each { DataCell cell ->
    entities << cell.getMemberName("Entity")
}
if (!entities.isEmpty()) {
    operation.grid.getSmartPush("Plan to Reporting").execute(
        ["Entity": entities.collect { "\"$it\"" }.join(", ")])
}

// Or run a whole data map, clearing the target region first
operation.application.getDataMap("Plan to Reporting").execute(true)

Push the narrowest slice that's correct. Pushing the whole year for every entity on every save is the most common reason a form starts to feel slow.

Habits that keep Groovy rules maintainable

  • One job per rule. A rule that validates, calculates, pushes and emails is hard to test and harder to change.
  • Write down why. A comment on top that says what the rule is for, who asked for it and which decision it implements saves the next developer an afternoon.
  • Log what you decided, not every cell. "Calculating 3 edited entities: CC4100, CC4110, CC4120" is useful. Ten thousand lines of cell values are not.
  • Handle #MISSING explicitly. cell.missing is not the same as zero, and treating it as zero quietly creates data.
  • Keep rules in version control alongside the requirement they implement, so a change to one prompts a look at the other.

Where EPM Agent fits

EPM Agent's build agents write business rules as readable specifications from the project's reviewed requirements, and compilers turn those specifications into the application's native format. Nothing reaches a production environment until a person approves it. See how artifact builds work, or read how one decision travels from a workshop to a build.

See EPM Agent on a project like yours.

A fictive engagement end to end: a meeting, the knowledge it creates, and the artifacts built from it.