Thursday, July 13, 2017

Quick July-2017 PBCS Update - Audit & Groovy Java API URL

PBCS Audit Feature

Did you notice in your Test POD the newest card "Audit" in "Application" cluster?



I did not read about it in July's Planning and Budgeting update maybe because it's already in the previous releases but maybe in a different place (Activity Reports.)....



The different is in Activity Reports you download or view the whole lot (data, metadata changes etc) unlike the new Audit feature, if you click on configure you get to selected the type of data you want to track for auditing.


Now if you change some data



You can see the records in Audit, you can filter for the audit transaction type (Data, metadata, rule...) for a specific date range, and you can export and delete the records.






If you click "Actions"








You can export the same in Excel csv (you'll get a similar file format to Activity Report's downloadable reports), and you can delete all records or a specific type only.










Groovy Java API reference link

The Groovy Java API reference library can now be accessed from:

http://docs.oracle.com/cloud/latest/epm-common/GROOV/


After 8th of August the Groovy Javadocs Academy link in your POD will be re-directed to that link.

This means, it's even easier to access the library without having to login to your service to access the documentation.




Saturday, July 8, 2017

On the fly Metadata creation, and advanced data validations with Groovy

Yes, I'm still writing about Groovy, if you are starting to feel bored about it then you are probably still not aware how powerful and revolutionary this recent addition is, it is not a "nice to have" feature, it's a lot more than that! I don't know how I wrote this post, I woke up at 5 AM and couldn't sleep so  thought I should utilize my weekend in a proper way! I'm also running a 10 k race tomorrow, so my apologies in advance for the typos, please ignore and focus on the content. 😉

Oracle was kind enough to give few use cases for Groovy in their library, but the issue is without having media attached to them (pictures and videos) it may be a bit difficult to fully grasp the beauty, power and awesomeness behind the lines and visualize it, so I put up a small demo to share with you.

I built this demo largely borrowing the logic of the following API examples, with my own additions and changes:

1. Multi line script to demonstrate creation of metadata and data with validations
2. Multi line script to demonstrate advanced data validations


This demo will show:

Creation of Metadata on the spot
Run time prompt validations
Data form validations
💥Cross cube validations💥

I will show the demo first, and later share the technical part with more details.

The example is about defining product definitions (min max quantity, discounts and prices..) and taking new orders based on those products, so without further ado, I have a "Product Order" cluster with two cards (Define Assumptions which is a data form pointing to one cube, and Add Order is another data form pointing to another cube).



I will start by defining my assumptions, as shown below I have one row (Product_1) with Min Quantity, Max Quantity, Max Discount, Standard Price and Price Adjustment Percentage values. In a nutshell for Product_1 orders must be minimum 100 and maximum 200 with a standard price of 1200 and discount available is  10%




This form is showing all available products (Children of Total_Product)


I also have a menu attached to the form "Add New Product", so let me go ahead and add a new product, I have to provide the parameters (quantity, discount and price) and in this instance I did not specify any validation, I did not even ask for the Product code/name for the new member which I will show later.


So after launching the rule, a new product member is added with the given assumptions.


I'll go ahead and add one more product, and enter the assumptions for the three products as shown below.




And you can see from the dimension outline the new members are added. (By default they took the prefix Product_ )




Now I'm done (for now) with defining the assumptions, I will go to "Add Order" and create a new order.




My Product Order form which is pointing to a separate cube, and I'm using a hierarchy driven smart list to assign the Product for every order. (I'm not going to explain the hierarchy driven smart list bit so if you're not familiar with it then I suggest you read Celvin's post , if you're from TM1 or IBM Planning Analytics background it's similar to pick lists which I wrote about here )

In this form I have a couple of validations:

1. Quantity must be within the Product Min-Max range defined in the Assumptions form (which happens to be in a separate cube)
2. Price must not be lower than the standard price plus the adjustment percentage defined for that product
3. Customer Code must start with E followed by five digits, for example E12345
4. Email Contact must be a proper email format




If you click on Product. cell you'll get the hierarchy driven smart list drop down:




Now,  will enter the order details as shown below, I entered a wrong customer code and invalid email id:



What happens when I save? Nothing gets saved, because of the validations



The validation error messages




I will change the values to the proper format and save again.









So far so good, OK I'll add a new line for a new order (I have a menu attached to the from to add new lines), I also have the same validations for customer code and email address at the run-time prompt level which will stop the rule from running if the prompt values are invalid:

I gave a wrong customer code format and tried to launch the rule





Rule did not launch, I need to enter the correct customer code format and then launch again to add the new line as shown below, I also did not specify the name or number of the item. 


In the old days of Essbase and Planning we used to create generic members (Line 1 to 100) and create a rule to loop the 100 lines and create a block for the next available member, this example however is fundamentally different because I'm adding a new member all together as shown in my dimension outline.



So now back to my new item, I will assign a product number of the order, specify the quantity and price, if you remember my Product 2 assumptions I had a minimum order of 150 defined with discount percentage set at 5%) so what happens if I save the form? I'll get a validation error telling me exactly what went wrong (In this case I entered 10 where I'm allowed to enter a range of 150 to 250)  as shown below.





This is how awesome and extremely powerful (if not mighty) Groovy is, in one cube I'm validating the order details data entered against product assumptions from a separate cube, the assumptions are entered at Product dimension level, and the order details data I'm validating is entered in the Account dimension linked by a hierarchy driven smart list.

Back to the example now, I'll change the quantity to fit within min-max range and save the form.



I'm done with the second order, I will go add a new order for Product 3 with 250 items at the price of 900, this is way below the allowed discount but I'm giving a note (the customer is a friend of my girlfriend and I'm trying to give him a deal).


Unfortunately, the order can't be saved because the price is lower than 1350 (Product 3 has standard price of 1500 and 10% discount)

This means I can't give that price and I need to change it.



What happens if I change the product for a saved order and it happens to be invalid for the new product? let's try this, first I'll add another Product (Product_4) and define the assumptions.





I will change the order details of my first order Product 4 and save.




I got two validation messages telling me exactly what the problem is and the allowed value/range , one for the quantity and another for the price as per the assumptions defined for Product 4.






So I'm left with no option but to change the order details and save the form again.




And life goes on from now on 😉


Groovy scripts and other artifacts:


Add New Product:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
/*RTPS: {MinQty} {MaxQty}  {Discount} {StdPrice} {PriceAdjPercentage} {Scenario} {Year} {Version}*/
def rowDimensions = operation.grid.rows.headers.essbaseMbrName
int nextProductCounter = rowDimensions.size() + 1
String nextProduct = "Product_$nextProductCounter"
Dimension productDim = operation.application.getDimension("Product")
Member parentProduct = productDim.getMember("Total_Product")
Map newProduct = parentProduct.newChildAsMap(nextProduct)
// Save the new Product
Member product = productDim.saveMember(newProduct, DynamicChildStrategy.ALWAYS_DYNAMIC)
// Generate the calc script to save product average price
"""Set CreateNonMissingBlk On;
Fix(${fixValues(rtps.Year, rtps.Scenario, rtps.Version, product)}, "BegBalance","No Plan Element")
"OEP_No Entity"(
                "Min Quantity" = $rtps.MinQty;
         "Max Quantity" = $rtps.MaxQty;
         "Max Discount" = $rtps.Discount;
         "Standard Price" = $rtps.StdPrice;
         "Price Adjustment Percentage" = $rtps.PriceAdjPercentage;
)EndFix;"""




Validate Order Details:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
class ProductData {
    Integer Product
    DataGrid.DataCell minQty
    DataGrid.DataCell maxQty
    DataGrid.DataCell standardPrice
    DataGrid.DataCell maxDiscount

    public String toString() {
        return "minQty: ${minQty?.formattedValue}, maxQty: ${maxQty?.formattedValue}, standardPrice: ${standardPrice?.formattedValue}, maxDiscount: ${maxDiscount?.formattedValue}"
    }
}

// Create a resource bundle loader containing localized messages needed by this rule.
def mbUs = messageBundle( ["validation.missingmember.product":"No Product found."] )
def mbl = messageBundleLoader(["en" : mbUs]);

//Build DataGrid for Product Assumptions
Cube driverCube = operation.application.getCube("OEP_FS")

DataGridDefinitionBuilder builder = driverCube.dataGridDefinitionBuilder()
builder.addPov(['Years', 'Scenario', 'Period', 'Version', 'Entity', 'Plan Element'], [ ['FY17'], ['OEP_Plan'], ['BegBalance'], ['OEP_Working'], ['OEP_No Entity'], ['No Plan Element'] ])
builder.addColumn(['Account'], [ ['Min Quantity', 'Max Quantity', 'Standard Price' ,'Price Adjustment Percentage'] ])
builder.addRow(['Product'],  [ ['ILvl0Descendants("Total_Product")'] ])

DataGridDefinition gridDefinition = builder.build()

// Load the data grid from the driver cube
DataGrid dataGrid = driverCube.loadGrid(gridDefinition, false)

// Create a map of product data by product name from the data grid.
def productDataMap = new HashMap()

StringBuilder scriptBldr = StringBuilder.newInstance()
if(dataGrid) {
    println("dataGrid is not null")
    GridIterator itr = dataGrid.dataCellIterator('Min Quantity')
    itr.each {
        def productData = new ProductData()
        productData.minQty = it
        productData.maxQty = it.crossDimCell('Max Quantity')
        productData.standardPrice = it.crossDimCell('Standard Price')
        productData.maxDiscount = it.crossDimCell('Price Adjustment Percentage')
        productDataMap[(it.getMemberName('Product'))] = productData
        println(it.getMemberName('Product') + ": " + productData)
    }
}

DataGrid grid = operation.grid

// Construct an iterator that iterates over all data cells containing the Product member.
GridIterator itr = grid.dataCellIterator('Product.')

// Throw a veto exception if the grid has at least one cell but does not contain any cells containing the Product member.
if(!grid.empty && !itr.hasNext()) {
    // Found 0 cells with Product
    throwVetoException(mbl, "validation.missingmember.product");
}

// Validate the values in the grid being saved against the values in productDataMap.
itr.each {
    ProductData productData = productDataMap[it.DataAsSmartListMemberName]
    if(productData == null) {
        println("Unable to locate Product data for: ${it.DataAsSmartListMemberName}, with data value: ${it.formattedValue}" )
    } else {
        DataCell quantity = it.crossDimCell('Quantity')
        if(quantity == null)
        println("Unable to locate quantity")
        else if(quantity.data < productData.minQty.data || quantity.data > productData.maxQty.data) {
            quantity.addValidationError(0xFF0000, "Quantity is not within Minimum($productData.minQty.formattedValue) - Maximum(($productData.maxQty.formattedValue) range.")
        }
        DataCell customerPrice = it.crossDimCell('Price')
        Double discount = ((1 - productData.maxDiscount.data) * productData.standardPrice.data)
        if(customerPrice == null)
        println("Unable to locate discount")
        else if(customerPrice.data < discount) {
            customerPrice.addValidationError(0xFF0000, "Can't go for discount lower than : $discount ")
        }
        DataCell customerCode = it.crossDimCell('Customer Code')
 if (customerCode.formattedValue ==~ /^(?!(E[0-9]\d{4})$).*/){
   customerCode.addValidationError(0xFF0000, "Customer Code must start with capital E followed by five digits (for example E12345)")
  }
 DataCell customerEmail = it.crossDimCell('Email Contact')
 if(customerEmail == null) {
     println("No email") 
  } else if (customerEmail.formattedValue ==~ /^(?!(^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[A-Za-z]{2,3}(\.[A-Za-z]{2})?$)).*/){
   customerEmail.addValidationError(0xFF0000, "Enter a valid email address.")
  }
    }
}

I won't explain every line (at least not in this post) but I'll highlight the important bits:

This section creates a data grid for the product assumptions (which we will use to validate the entered data in the form) and loads the data in the grid.


//Build DataGrid for Product Assumptions
Cube driverCube = operation.application.getCube("OEP_FS")

DataGridDefinitionBuilder builder = driverCube.dataGridDefinitionBuilder()
builder.addPov(['Years', 'Scenario', 'Period', 'Version', 'Entity', 'Plan Element'], [ ['FY17'], ['OEP_Plan'], ['BegBalance'], ['OEP_Working'], ['OEP_No Entity'], ['No Plan Element'] ])
builder.addColumn(['Account'], [ ['Min Quantity', 'Max Quantity', 'Standard Price' ,'Price Adjustment Percentage'] ])
builder.addRow(['Product'],  [ ['ILvl0Descendants("Total_Product")'] ])

DataGridDefinition gridDefinition = builder.build()

// Load the data grid from the driver cube
DataGrid dataGrid = driverCube.loadGrid(gridDefinition, false)


After Grid is created and loaded, this iterator will fill the object productData of class ProductData (defined at the beginning) and use it for validations.



if(dataGrid) {
    println("dataGrid is not null")
    GridIterator itr = dataGrid.dataCellIterator('Min Quantity')
    itr.each {
        def productData = new ProductData()
        productData.minQty = it
        productData.maxQty = it.crossDimCell('Max Quantity')
        productData.standardPrice = it.crossDimCell('Standard Price')
        productData.maxDiscount = it.crossDimCell('Price Adjustment Percentage')
        productDataMap[(it.getMemberName('Product'))] = productData
        println(it.getMemberName('Product') + ": " + productData)
    }
}


A sample job console log after running this rule:


Add New Order:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/*RTPS: {CustomerCode} {Email} {Year}  {Scenario} {Version}*/
def mbUs = messageBundle(["validation.invalidcode":"Customer Code is invalid: {0} (Ex Valid Customer Code E12345","validation.invalidemail":"The email format is wrong {0}."])
def mbl = messageBundleLoader(["en" : mbUs]);
def rowDimensions = operation.grid.rows.headers.essbaseMbrName
int nextItem = rowDimensions.size() + 1
String nextLineItem = "LineItem_$nextItem"
//validate rtp values
validateRtp(rtps.CustomerCode, /^E[0-9]\d{4}$/, mbl, "validation.invalidcode", rtps.CustomerCode);
validateRtp(rtps.Email, /^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+\.[A-Za-z]{2,3}(\.[A-Za-z]{2})?/, mbl, "validation.invalidemail", rtps.Email);
Dimension customDim = operation.application.getDimension("Entity")
Member parentOrder = customDim.getMember("Total_LI")
Map newLineItem = parentOrder.newChildAsMap(nextLineItem)
// Save the new line item
Member lineItem = customDim.saveMember(newLineItem, DynamicChildStrategy.ALWAYS_DYNAMIC)
// Generate the calc script to save the line item
String script = """Set CreatenonMissingBlk On;
Fix(${fixValues(rtps.Scenario, rtps.Year, rtps.Version, lineItem)},"BegBalance")
"No_Account"(
"Customer Code" = $rtps.CustomerCode;
"Email Contact" = $rtps.Email;
)
EndFix"""
println script
return script.toString()



Product smart list:



Product Assumptions and Product Order Forms (just to show they are built for different cubes):









That is it, this was a lengthy post but I really hope it can help you better understand how we can embed Groovy and use it in our solutions.





Friday, June 30, 2017

Groovy, E/PBCS, and Random() stuff....

My last few posts were talking about EPBCS and the newest (most powerful and exciting) feature added recently to the cloud which is Groovy scripting! My background is computer science and naturally, I was super excited about the latest addition and started instantly writing scripts and playing around with it.

Thanks to Celvin Kattookaran who read the Groovy posts and his valuable feedback, he suggested a simpler way of writing the code, and after we exchanged some comments it turned out I was using an old version of the API and he got me in touch with the Oracle Calculation Manager development team, who were kind enough (Thank you Ujwala Maheshwari!) to call me and give me some updates and insights on the latest Groovy scripting feature, as well as the current API library and some of the examples provided. So I thought I should share some of the points/findings:


Some of the pre-built EPBCS Groovy rules are written using the old API version

This is going to be updated soon (maybe as early as August 2017), Good thing that the API library has a lot of useful examples, to access this library go to Academy Groovy Javadocs and simply enjoy! The documentation provided by Oracle here is superb, very clear, powerful and well-written examples, this must be in your browser's favorites



Groovy is simpler than Java

I come from computer science background, I learned to program first using low-level languages (Assembly) and then moved to high-level languages (Pascal, C, VB and Java), why am I mentioning this? because you're very likely to start scripting in Java and totally forget how awesome and groovy Groovy the language is! So what is wrong with writing code in Java? Nothing, but if you can achieve the same result with fewer lines that look more aesthetic then why not?

I will give a very simple example to highlight the above, consider a script that prints Hello World and the current day, this is the first thing you'll learn how to write in any programming language, I'll write the same in Java and Groovy and see where they are different.

Java


1
2
3
4
5
6
7
8
9
import java.util.Date;
import java.text.*;
public class Main{
    public static void main(String[] args) {
       DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyyy"); 
       Date date = new Date(); 
       System.out.println("Hello, World! Today is: " + dateFormat.format(date));
    }
}

Output


Groovy


1
2
3
4
import java.text.*
DateFormat dateFormat = new SimpleDateFormat("EEE, MMM d, yyyyy")
Date date = new Date()
println("Hello, World! Today is: " + dateFormat.format(date))

Output


So, what do you think? Groovy certainly looks nicer and more concise, I wanted to add the date bit because I wanted to highlight some differences between Java and Groovy in the given example:

1. In Groovy, java.util package is imported by default, hence the import line is missing from my Groovy script unlike Java where you need to import every package/class you intend to use.

2. In my Groovy script I don't have a class and method declaration like Java, so if you just want to print Hello World you just need


println("Hello World!")

3. To get formatted dates, you need DateFormat and SimpleDateFormat classes, in both Groovy and Java you need to import the classes

4. Another difference is the semi-colons, in Groovy I don't need to end my lines with ";"

For a more detailed list of differences click here



You can write a perfectly functioning Groovy script and then realize it's really a Java script

One of the first scripts I wrote when I was testing Groovy in EPBCS was a data validation script to prevent users from entering negative values, so the first time I wrote the code it was exactly like this:



 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
EPMApplicationShell appshell = new EPMApplicationShell()
DataGrid grid = null;
// exit if rule is executed from Rules launcher
try {
grid = appshell.getCurrentGrid()
} catch(BindingsMissingException) {
return  '''BegBalance (
          @Return("Please run the rule from the dataform"),Error);
       )'''
}
//validate negative value
GridIterator itr = grid.dataCellIterator()
itr.each{ 
DataCell dc = it
if ((dc.isEdited()) && (dc.data <0)) {
dc.addValidationError(0xFF6347,"Cannot enter negative numbers")
}
} 


Lines 1 to 10 are there to make sure the script is launched in a form/grid and not Rules launcher, I borrowed this code from Trend Calculation Groovy rule in PBCS, and apparently this is the alpha version and we no longer need to define appshell variable or write the try catch statement. (leave it for now, I'll come back for it).

Lines 11 to 18 Invokes a Grid Iterator and checks edited data cells, and if negative values are found then throw an error.

Now, the following is the refined code:



1
2
3
4
// Validate negative value 
operation.grid.dataCellIterator{DataCell cell -> cell.edited}.each { DataCell cell -> 
if ((cell.data < 0)) 
cell.addValidationError(0xFF6347, "Cannot enter negative numbers") }

Oracle Calc Manager were kind enough to re-write my code and they explained the redundant bits.

Lines 1 to 10 are no longer needed and is simply replaced with "operation.grid", so when you try to run the rule above from Rules Launcher it will throw an error "grid not found" because of operation.grid.* which assumes there is an active grid, otherwise throw error and break.

Lines 12 to 18 can be replaced by a simple Closure block, coming from Java background the concept is still new to me, but that is what makes Groovy beautiful and easy to use!


Groovy in Action

Want to learn more about Groovy? Check this out, I'm enjoying this book and most importantly it is really fun to read! It is not written in a typical academic computer science text book style, which means it is fun to read, I don't remember ever enjoying reading my text books back at university. (You can get a combo deal at manning publications which includes a pdf, epub, and soft cover paper version)





What kind of subscription you need to have Groovy your POD? PBCS? PBCS + 1 module? or EPBCS?

Thanks to Shankar Viswanathan  Oracle Planning Product Management, I got this point clarified:

Groovy is technically made available for EPBCS App type which is different from saying it is only for EPBCS. There are three SKUs that customers can buy: PBCS; PBCS + 1 module option; EPBCS. If you buy the PBCS +1 module option you can still deploy the application as EPBCS App Type or convert from PBCS App Type to EPBCS App Type. It is just that contractually you can't deploy more than 1 module when you buy PBCS + 1 module. To get Groovy all you need is to have EPBCS App Type. To use groovy you don't even have to deploy any modules once you are in this EPBCS App Type. So technically it is available for PBCS as long as at least the PBCS + 1 module option is bought by the customer. You could be using just the custom cubes in EPBCS App Type and still use Groovy. There is no current plans to make it available for standalone PBCS. Hope this can be clarified in your future posts.



Yes, that is right you can have Groovy with PBCS as long as you go for the plus module option, if you ask me is it worth it? my answer is...




YES         YES       YES      YES