Groovy Cheatsheet

This section is meant as a quick library of copy/paste code snippets. For details on functions, refer to the API Documentation.

Calculated Field Set 

  • Get the current processed item (e.g., product):

    api.currentItem()

    Sometimes this does not work in the debug mode; then you can use:

    if (!api.isDebugMode()) {  return api.currentItem() }
    def currentItem = api.currentItem() != null ? api.currentItem() : api.getProduct(api.product("sku")) 
    
  • Get the attribute of the current product:
    • formula: Product("MatNr. 8 Stellen")
    • Groovy: api.product("MatNr. 8 Stellen")
  • Get the parameters for CFS:
    • return api.option("Add Products to Price Grid","Yes","No")?:"Yes"
  • Track the progress when running:
    Admin > Job/TaskTracking > find CFS by its ID

Products Table

  • Iterate through products:

    def prods = api.find("P", Filter.equal("attribute20", sku8))
    for (p in prods) {
      api.trace("Marking for recalculation", null, p.sku)
      api.update("P", [
        "sku" : p.sku,
        "attribute30" : "X"
      ])
    }

Price Parameter

  • To look up a certain row:
    • formula: VLookup(“<PP table name>", “<key of the desired row>")
    • Groovy: api.vLookup("Cockpit_Teile", "Value", "Teile") 
  • Iterate through all rows:

    def values = api.findLookupTableValues("Reaktivierte_Stati")
    if (values) {
      for (v in values) {
        def a = v.name
        def b = v.attribute1

Product Extension

This code shows how to get a value of the attribute name. It is not possible by default from Groovy because getExtension returns a list of records that contain original names "attribute1, attribute2....". 

Getting parameter from product extension by its label
def px1 = api.productExtension("L1_L2_prices")
if (px1) {
  def meta = api.find("PXAM", Filter.equal("name", "L1_L2_prices"), Filter.equal("label", "RCH1001"))
  def attrName = meta[0].fieldName
  def value = px1[0].get(attrName)
  return value
}
return null

Date Time Functions

def lastUpdate = api.product("lastUpdateDate")
api.trace("lastUpdate", null, lastUpdate)
def date = '12/01/2014 00:00:00'
def myDateTime = Date.parse( 'dd/MM/yyyy HH:mm:ss', date)
api.trace("myDateTime", null, myDateTime)
return lastUpdate > myDateTime

Debug:

api.trace("Product", null, product)

Global API Variables

If you use global variables, you need to check the settings of api.retainGlobal.

If the option 'api.retainGlobal defaults to TRUE' is enabled, then using api.global is enough.

If it is disabled, the calculation engine resets this variable to false in the beginning of each record calculation and that causes that the api.global map with all gathered data is lost. If you want to enable it for a particular logic, set api.retainGlobal = true in the first element in the first line of code! 

api.retainGlobal = true //optional (see above)
api.global.<variable> = “hello"

CRUD Operations

Add

def map = [
          pricelistId: plId,
          sku: item.sku,
          resultPrice: item.resultPrice,
          label: item.label,
          unitOfMeasure: item.unitOfMeasure,
          currency: item.currency,
          comment: item.comment
        ]
api.add("PLI", map)

Add or Update

def product = [:]
product["sku"] = “Product1"
product["label"] = “The Best Product"
api.addOrUpdate("P", product)
api.addOrUpdate("PX", ["name": "Scoring_MM", "sku": sku])
api.addOrUpdate("PGI", ["priceGridName" : "LifeCycleMonitor",
                        "sku" : currentItem.sku, "label" : currentItem.label])
def large = ["lookupTableId": pp.id, "lookupTableName": pp.uniqueName, "name": "L", "attribute1": percentileHigh, "attribute2": "999999999"]
api.addOrUpdate("MLTV", large)
  • When debugging a logic using Test Drive, this function will NOT perform the write operation – it will skip it. However, there is a checkbox (in Test Drive) to allow execution of write operations.
  • This operation will ONLY work in contexts that allow object modification (CFS, CalculationFlow and direct logic execution via JSON API).

Read Data and Search Any Table

api.find("PLI", Filter.equal("sku", mySku))

Iterate over Results of FIND Operation

As the Find operation may not give you all the results, but only 100 items or so, you can use this code:

def startRow = 0
while ( products = api.find("P", startRow, <filters>) ) {
	startRow += products.size()
	for(def product : products){
		//……...
	}
}

Update

// update the LAST_PROCESSED_ID in PricingParameters
def lt = api.findLookupTable("CopyCFS")
api.update("LTV", [
  lookupTableId : lt.id,
  name : "LAST_PROCESSED_ID",
  value : id
])

Delete

api.delete("PX", [
      name: "PMIntegration",
      id: id
])

Set Values in Extra Info Columns Attributes

This sample shows how to set values in additionalInfo[1,2,3] attributes (Extra Info columns) on Quotes and Agreements/Promotions via the header logic. 

//Contract header logic (PromotionManager)
cProcessor.updateField("ROOT", "additionalInfo3", "some text")


//Quote header logic (QuoteConfigurator)
quoteProcessor.updateField("ROOT", "additionalInfo3", "some text")

Get Value of Another Element of the Pricing Logic 

api.getElement("<element_name>")

Get Attribute Value by Name

api.getPropertyByElementName(pgi, "SomeLabel")

Syntax Check Hack

Sometimes the syntax check is ok but you still cannot save the logic. Then use:

api.isSyntaxCheck()

This will check if your code is ok, even if the validator does not evaluate it this way. See also How to Save Logic that Is Evaluated as Erroneous by Syntax Checker.

Custom Monitoring

def grafanaMetrics = [:]
grafanaMetrics["myCSFfinished"] = 1
api.sendMetrics()

Found an issue in documentation? Write to us.

Â