Interface PublicGroovyAPI


  • public interface PublicGroovyAPI
    This interface represents what can be reached in the Groovy element syntax as api. That api variable or binding is merely an instance of this interface to expose certain "safe" methods and functionality.

    Caching usage
    The API exposes three ways to store transient and temporary data during formula executions. Each variant has its own specifics and therefore is not suitable for all use cases. The options are:
    • api.local
    • api.global
    • Shared Cache

    The first two can be understood as mere in-memory hash maps. For example, api.local.put("key","value") will work fine.
    The difference between them is the potential scope and retention of the contained data.

    api.local:
    This is a hash map that is available during the lifetime of exactly one logic execution. It can (and should) be used to store intermediate results that need to be accessed by other subsequent logic elements.

    api.global:
    By default, api.global is very similar to api.local. Without any further settings, the only difference is that api.global is also available in Groovy library functions (while api.local is not).
    However, by setting api.retainGlobal = true you can instruct the formula engine to keep the hash map in between logic runs. It works between line items and, in case of Quotes, Contracts and Rebate Agreements, between the header and the line items (but only in the pre-phase, not in the post-phase). The values are also carried forward between two list calculation passes (i.e. form initial run to dirty item run; ONLY in non-distributed mode.).
    Important notes:
    retainGlobal can be set to true either in the logic or globally in Configuration > All Modules > General Settings > api.retainGlobal defaults to TRUE. retainGlobal is effective only once. In order to keep it for the 3rd item as well (and so on) you need to call it in every formula execution.
    api.global data also stick to their execution thread. That means that they are NOT shared between the different parallel executions of a distributed calculation. It effectively builds up multiple caches. Another side effect of this is that api.global is not retained and passed to a subsequent calculation pass if the original calculation was in a distributed mode.

    Shared Cache:
    The main limitation of api.global is the restriction of its availability to the current execution thread. In a distributed calculation however, there are multiple threads and even multiple servers involved in the calculation. If all these should share a single cache, you must use the shared cache. The shared cache is even available to different calculations (such as other lists or list & CFS or dashboard logic etc). Be careful with key naming so that you do not mix and match data.
    These advantages come at a cost: Due to the distributed "superglobal" nature, the read/write operations of that cache are slower compared to a real local in-memory map. Use the shared cache only for data that is expensive to calculate or for avoiding frequent database calls. Data in the shared cache expires automatically, the TTL is extended everytime a key is written or read. Values stored are of the String type only. Serialization and deserialization of other objects like dates and numbers are to be done in logic itself.

    Object modifications
    The API contains methods to manipulate data (add, addOrUpdate, delete, etc). These methods can only be used in certain formula contexts (otherwise they are ignored). These contexts are:
    • From within a CFS execution (non-distributed only)
    • From within a calculation flow
    • From within a direct logic execution via JSON API

    On top of this, some restrictions apply which data objects can be manipulated - i.e. not every possible object can be modified. Currently available whitelisted typecodes are:
    • All customer extension types
    • All product extension types
    • All matrix price parameter values and normal price parameter values (LTV) as well as price parameter header (LT)
    • PGI and XPGI
    • PLI and XPLI
    • MPLI
    • P
    • C
    • PCOMP
    • PDESC
    • PGI
    • TODO
    • Data export, import and archive
    • Method Detail

      • isSyntaxCheck

        boolean isSyntaxCheck()
        Returns true if the logic/formula is being executed in the syntax check mode. The syntax check mode is a special type of execution run used to determine the logic input parameters in the configuration dialogs, where the logics are selected (e.g. in configuration of LPGs, PLs or dashboards). These input parameters are also used on document line items (like Quote, Contract, etc) The syntax check mode runs against no calculable item (in context of no object), so all the functions that depend on item data (e.g. product() or currentItem() as well as getElement(String)) produce null or mocked values.

        Note: The best practise is to gather all parameters in the first elements of the logic and then abort the calculation after all parameters are gathered, otherwise all code which depends on the item data will need a special treatment (it would have to be surrounded using this function).

        Example:

        Element Amount:

         return api.decimalUserEntry("Amount")
         
        Element Comment:
         return api.stringUserEntry("Comment")
         
        Element SyntaxCheckAbort:
         if (api.isSyntaxCheck()) {
           api.abortCalculation()
         }
         
        Returns:
        true if the logic is executed in the syntax check mode
      • isDebugMode

        boolean isDebugMode()
        Returns true if the logic is being executed via the UI "Test Logic" execution mode. Because during "testing" the logic does not have all information available, you can use this functions to detect this mode, and mock some necessary data, if they're not available.

        For example, when you test the Quote line item logic, then you usually need the Customer Id, which is often selected only on the header of the Quote. But since you test the Quote Line logic standalone, the information from header is not available. Using the isDebugMode you can detect this special execution mode and supply/mock a particular customerId for testing purposes

        Code sample (Quote Line item logic):

         if(api.isDebugMode()) {
             input.Customer = "CD-00004"      // in regular execution, the input.Customer would be inherited from header input
             input.DeliveryType = "Standard"  // in regular execution, the input.DeliveryType would be inherited from header input
         }
        
         def country = api.customer("Country", input.Customer)
         
        Returns:
        true if the logic is being executed in the "Test Logic" mode
      • isDistributedMode

        boolean isDistributedMode()
        Returns true if the calculation is executed in the distributed mode. Useful to suppress warnings (or not execute methods) for operations that do not work in the distributed mode. These operations are basically all write operations that affect other items. Examples: all object modification ops (add, addOrUpdate, update, delete), marking other items dirty
        Returns:
        true if executed in the distributed mode
      • getGlobal

        Map<String,​Object> getGlobal()
        A publicly available cache (as a hashmap) for storing and sharing values across logic elements. If api.retainGlobal is set to true, this map will also be available with the entire list calculation, i.e across item boundaries. It can be also accessed directly as api.global. Important: This map must be treated as a cache. It means that the logic should never rely on the cached values, as in various situations this cache is purged or structured differently. For example, in a distributed calculation, every calculation thread has its own cache; or in a multi-pass list calculation, the subsequent passes may not have the cache of the previous pass available. The system always tries to make it available, but the logic should never rely on it.
        Returns:
        the hashmap
      • putGlobal

        void putGlobal​(Map<String,​Object> globalVars)
        Puts an entire map of variables into the global cache.
        Parameters:
        globalVars - The map of variables to put into the global cache
      • getCalculationContext

        String getCalculationContext()
        Retrieves the CalculationContext of the logic evaluation (logic element group).
        1. For a PA Calculation or Flush logic this can be (from PriceFxInterface):
          • FORMULAELEMENTGROUP_DM_INIT = "init" - executed before rows
          • FORMULAELEMENTGROUP_DM_ROW = "row" - executed for every line of the Target/Source
          • FORMULAELEMENTGROUP_DM_SUMMARY = "summary" - executed after rows
        2. In RebateAgreement calculation there is:
          • FORMULAELEMENTGROUP_RM_AGREEMENT = "agreement"
          • FORMULAELEMENTGROUP_RM_AGREEMENT_READONLY = "agreementReadOnly"
          • FORMULAELEMENTGROUP_RM_REBATERECORD = "rebateRecord"
        3. In the Optimizer module, when evaluating Model formulas, there is:
          • FORMULAELEMENTGROUP_MODEL_DEFINITION = "definition"
          • FORMULAELEMENTGROUP_MODEL_CALCULATION = "calculation"
          • FORMULAELEMENTGROUP_MODEL_ANALYSIS = "analysis"
          • FORMULAELEMENTGROUP_MODEL_FINALIZATION = "finalization"
          • FORMULAELEMENTGROUP_MODEL_RECORD = "record"
        Returns:
        CalculationContext as String
      • getBatchInfo

        List<String[]> getBatchInfo()
        Gets the info about the current batch of items being calculated by a calcuation thread. The calculation batch size is defined by a server variable calculationTasks.commitBatchSize and by default it is 200 records. For the best use, use the functions from the Shared Library.
        Returns:
        List of arrays [sku, key2] for PLI, XPLI, PGI, XPGI contexts or [itemId, typedId] for CFS logics run on P, PX
        See Also:
        SharedLib/elements/BatchUtils.groovy
      • getId

        Long getId​(Object obj)
        Returns the ID part of an object. The method tries to be smart and extracts also IDs from maps or typedId strings.
        Parameters:
        obj - The given object (Map)
        Returns:
        The ID of the object
      • getElement

        Object getElement​(String name)
        Gets the result value returned by the previous logic element.

        Note: Instead of this function, you can also use out.<ElementName> (or output.<ElementName>).

        Warning: During Syntax Check mode, this function returns mock results, not the real ones.

        Parameters:
        name - The name of the logic element which value you want to retrieve
        Returns:
        The value or null if the element is not found. During the syntax check mode the result value is mocked.
      • getSecondaryKey

        Object getSecondaryKey()
        Same as api.currentItem("key2"). Retrieves the secondary key (field "key2") of a matrix item record. Applicable in the following contexts:
        • matrix price grid (XPGI.key2)
        • matrix price list (XPLI.key2)
        • matrix simulation (XSIMI.key2)
        Returns:
        The value of the secondary key or null if calculating a single item record (= not a matrix item record from the list above)
      • getBinding

        Object getBinding​(String name)
        Gets a named binding variable from a library function. Example:

        In a workflow formula, the workflow can be referenced in a Groovy element directly by the binding/variable "workflow": workflow.addApprovalStep("First Approval")

        However, this does not work from a library function as this script does not have the binding available. You need to use:

         api.getBinding("workflow").addApprovalStep("First Approval")
         
        Parameters:
        name - The name of the variable
        Returns:
        The binding
      • targetDate

        Date targetDate()
        Returns effective/target date of the document being calculated. (It retrieves this mandatory parameter targetDate from the current execution context.)

        The target date is usually new Date() by default or overriden by user at:

        • Quotes: in the Quote view - entered via Effective Date input parameter
        • Price lists: in the Price list creation dialog - entered at step/tab Get parameters
        • Price grids: in the Price grids overview window - in Target date column
        • PA calculation dataloads: in Dataload definition, under Calculation tab
        • Calculation flow: in Calculation flow detail, under Target date column

        Example:

         api.targetDate().format("yyyy-MM-dd")
         
        Returns:
        The targetDate date
      • calendar

        Calendar calendar()
        Gets a java.util.Calendar object initialized with the current targetDate (or new Date() if no target date is given). Used for adding days/months/year and/or setting hours, minutes, seconds.

        Example:

         def months = 6
        
         def calendar = api.calendar()
        
         // adds months to the date
         calendar.add(Calendar.MONTH, months)
         calendar.set(Calendar.HOUR_OF_DAY, startHour)
         calendar.set(Calendar.MINUTE, 0)
         calendar.set(Calendar.SECOND, 0)
        
         // return the date 6 months later after targetDate at 00:00:00
         calendar.getTime()
         
        Returns:
        The initialized Calendar object
      • calendar

        Calendar calendar​(Date date)
        Gets a calendar object initialized with date.

        Example:

         def months = 6
         def targetDate = api.targetDate()
        
         def calendar = api.calendar(targetDate)
        
         // adds months to the date
         calendar.add(Calendar.MONTH, months)
         calendar.set(Calendar.HOUR_OF_DAY, startHour)
         calendar.set(Calendar.MINUTE, 0)
         calendar.set(Calendar.SECOND, 0)
        
         // return the date 6 months later after the given date at 00:00:00
         calendar.getTime()
         
        Parameters:
        date - The date to initialize the calendar with
        Returns:
        The initialized Calendar object
      • random

        Random random()
        Provides the access to the standard java.util.Random generator instance created for the duration of the calculation task (= not get recreated for each logic element evaluation).

        Example 1:

         def randomPct = (90 + api.random().nextInt(20)) / 100
         // randomPct contains the random Integer number between 90 (inclusive) and 110 (exclusive)
         

        Example 2:

         def random = api.random().nextLong()
         // random contains the random Long number e.g. -2249116201139970752
         
        Returns:
        The java.util.Random generator instance created for the duration of the calculation task (i.e. does not get re-created for each formula (element) evaluation).
        See Also:
        https://docs.oracle.com/javase/8/docs/api/java/util/Random.html
      • newDatamartSlice

        Object newDatamartSlice​(String dateFieldName,
                                Object... timePeriodsAndProductAndCustomerGroups)
        Creates a new DatamartSlice, which allows setting filter criteria along the Time, CustomerGroup, ProductGroup or other dimensions in a Datamart, initialized with the name of the time dimension field and an optional set filter criteria.
        Parameters:
        dateFieldName - Name of the time dimension field
        timePeriodsAndProductAndCustomerGroups - TimePeriod, CustomerGroup, ProductGroup filters
        Returns:
        The initialized DatamartContext.DataSlice object
      • datamartFilter

        Filter datamartFilter​(Object groupOrSlice)
        Translates a CustomerGroup/ProductGroup/DMDataSlice to its equivalent filter representation, mapping the domain level field names to the corresponding Datamart field names in the process.

        Note: A DMDataSlice object can be instantiated by api.newDatamartSlice, or in a Rebate calculation context, referenced by the 'calulationBase' binding.

         def filter = api.customerGroupEntry("Customer Filter")
         return filter != null ? api.datamartFilter(filter) : Filter.custom("1=1")
         
        Parameters:
        groupOrSlice - The CustomerGroup/ProductGroup/DMDataSlice to translate into Datamart level filter criteria
        Returns:
        Filter object representing either the CustomerGroup/ProductGroup dimension slice or the passed slice in the Datamart
      • datamartQuery

        Object datamartQuery​(Object... queryAndDatamartAndProjectionsAndFilters)
        This method is deprecated and exists only for backward compatibility for older in-production formulas. Use the Groovy query API instead (see DatamartContext). Runs a query against a PA Datamart. The query is only executed once in the scope of a calculation job (PL generation etc.). The query is identified by the first argument. This is also the 'handle' by which datamartLookup refers to the result set of the query.
        Parameters:
        queryAndDatamartAndProjectionsAndFilters - The first argument is the query ID/handle, subsequent arguments are either DM field names (projections) or filter objects.
        Returns:
        The numbers of rows in the result set. The actual result set data is stored in memory for a subsequent lookup by datamartLookup(...).
      • datamartLookup

        Object datamartLookup​(Object... queryAndProjectionsAndFilters)
        Deprecated.
        Use DatamartContext.executeQuery(DatamartContext.Query), net.pricefx.formulaengine.DatamartContext#executeSqlQuery(String, DatamartContext.Query...) or DatamartContext.streamQuery(DatamartContext.Query)
        This method is deprecated and only exists for backward compatibility for older in-production formulas. Use the Groovy query API instead (see DatamartContext). Looks up rows in the result of a datamartQuery(...) call.
        Parameters:
        queryAndProjectionsAndFilters - The first arguments is the ID/handle from a datamartQuery(...) call. Subsequent arguments refer to projections specified in the datamartQuery call or filter objects leading to additional filtering of rows in the result set.
        Returns:
        A single primitive value if the result of the lookup results in one row for just one projection. A list of values if the result is multiple rows for one projection. A map of (field name, value) pairs for a single row result with multiple projections. A Matrix2D object for multiple rows and projections.
      • getDatamartContext

        DatamartContext getDatamartContext()
        Provides an API for querying and loading PA data. The most common cases are:

        Example 1:

         def ctx = api.getDatamartContext()
        
         def dm = ctx.getDatamart("Transactions_DM")
        
         def query = ctx.newQuery(dm, true)
             .select("ProductGroup")
             .select("SUM(SalesValue)")
             .where(
                 Filter.equal("Year", "2019"),
             )
             .groupBy("ProductGroup")
             .orderBy("ProductGroup")
        
         def result = ctx.executeQuery(query)
        
         return result?.getData()
         

        Example 2:

         def date = api.parseDate("yyyy-MM-dd", "2018-01-24")
         def week = api.getDatamartContext().calendar().getWeek(date)
         return week
         
        Returns:
        DatamartContext
      • getTableContext

        TableContext getTableContext()
                              throws Exception
        Provides an SQL query (SELECT only) interface to PA query results.
        Returns:
        TableContext
        Throws:
        Exception - if a DB connection cannot be established
      • getDatamartRowSet

        DatamartRowSet getDatamartRowSet()
        Available in a PA DataLoad context only, a DatamartRowSet provides access to the rows being loaded or calculated.
        Returns:
        The DatamartRowSet holding the data rows to load in the target FC.
      • getDatamartRowSet

        DatamartRowSet getDatamartRowSet​(String name)
        Available in a PA DataLoad context only, a DatamartRowSet provides access to the rows currently being loaded or calculated. The following Data Load types make use of rowsets:
        • 'Flush': The source rowset gives access to the DataFeed data rows, while the target rowset holds the rows to be loaded in the target DataSource (DS).
        • 'Calculate': The source rowset gives access to the source rows, which can either come from a DF or from the target FC being calculated. The target rowset holds the rows to be loaded in the target FC. Initially, this rowset will be empty unless the DL.withTargetSnapshot option is set, in which case the rowset will be pre-populated with the target FC rows in the scope of the DL (determined by the DL.filter).

        Example 1:

         def newRow = [
              "sku" : "1234456",
              "cost" : 123
         ]
        
         def target = api.getDatamartRowSet("target")
        
         // target is null when running the logic test execute, so you can use trace for debugging purposes
         if (target) {
             target.addRow(newRow)
         } else {
             api.trace("newRow", null, newRow)
         }
         

        Example 2:

         def source = api.getDatamartRowSet("source")
         def target = api.getDatamartRowSet("target")
        
         while (source?.next()) {
             def row = source?.getCurrentRow()
        
             // perform the required calculation of row
             target["TotalSales"] = ...
        
             // target is null when running the logic test execute, so you can use trace for debugging purposes
             if (target) {
                 target.addRow(row)
             }
         }
         
        Parameters:
        name - Either 'source' to select the source FC or 'target' to select the target FC rowset.
        Returns:
        The DatamartRowSet holding either the source or target rowset.
        See Also:
        getDatamartContext(), DatamartContext.newQuery(Table)
      • resetSKUContextSwitch

        void resetSKUContextSwitch()
        Resets a SKU context switch to the originally specified SKU.
        See Also:
        switchSKUContext(String)
      • product

        Object product()
        Retrieves the product object for the SKU currently being calculated (SKU in the context) The result product object is cached and the next call reads the value from cached record.

        Example:

         def item = api.product()
         def message = checkItem(item)
        
         def checkItem(item) {
             if (!item.attribute2) {          // Product group
                 return "Product group not set"
             } else if (!item.attribute5) {   // Manufacturer
                 return "Manufacturer not set"
             }
         }
         
        Returns:
        The full current product Map
        See Also:
        currentItem(), product(String), product(String, String), product(String, String, String, Object)
      • product

        Object product​(String attributeName)
        Retrieves the given attribute value from the Products table for the SKU being calculated (the SKU in the context). The product object is cached and the next call reads the value from the cached record.

        When reading the predefined columns, use their system names - e.g. label, unitOfMeasure.

        When accessing the attribute columns, preferably use their "Name" defined for the column, when you've set up the table. You can also use their system names (attribute1, ...), but it does not give you much information, which value you're reading.

        Special Use-Case: when you call the function with "sku" attribute, this specific call is optimized in the backend, so it does not make a lookup in the Products table, but instead returns the SKU value directly from the context.

        Side effect: During the Syntax Check mode, this functions triggers creation of the input parameter Product. But because Product is usually selected in another way (e.g. in Pricelist or Quote), this would apply only in rare use-cases.

        Examples:

         def label = api.product("label")
         def uom = api.product("unitOfMeasure")
         def productGroup = api.product("ProductGroup")  //  api.product("attribute1")
         def manufacturer = api.product("Manufacturer") //  api.product("attribute4")
         
        Parameters:
        attributeName - The name of the attribute column, which value we want to retrieve. For the customizable attributeX columns, it can be either in the form "attribute1" or the Name provided in the dialog Rename and Customize Column.
        Returns:
        The value of the attribute
        See Also:
        currentItem(String), product(), product(String, String), product(String, String, String, Object)
      • product

        Object product​(String attributeName,
                       String sku)
        Retrieves the given attribute value from the Products table for a given SKU.

        When reading the predefined columns, use their system names - e.g. label, unitOfMeasure.

        When accessing the attribute columns, preferably use their "Name" defined for the column, when you've set up the table. You can also use their system names (attribute1, ...), but it does not give you much information, which value you're reading.

        Example:

         def masterSku = ...
         def label
        
         if (masterSku) {
             // take the label from the masterSku item
             label = api.product("label", masterSku)
         } else {
            // take label from the item being calculated
            label = api.product("label")
         }
         
        Parameters:
        attributeName - The name of the attribute column, which value we want to retrieve. For the customizable attributeX columns, it can be either in the form "attribute1" or the Name provided in the dialog Rename and Customize Column.
        sku - The product
        Returns:
        The value of the attribute (or null if product not found)
        See Also:
        product(String), product(), product(String, String, String, Object)
      • product

        Object product​(String attributeName,
                       String sku,
                       String filterFormulaName,
                       Object filterFormulaParam)
        Retrieves the given attribute value from the product table for a given SKU. If the given SKU is null, filterFormulaName and filterFormulaParam are used to apply filter logic for the Product picker.
        Parameters:
        attributeName - The attribute whose value should be returned
        sku - The product
        filterFormulaName - Unique name of a formula that will be triggered when the Product picker opens
        filterFormulaParam - Additional data for filterFormula
        Returns:
        The value of the attribute (or null if product not found)
        See Also:
        product(String, String), product(String), product()
      • otherProduct

        Object otherProduct​(String parameterName,
                            String attributeName)
        Triggers a custom-named product picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        attributeName - The attribute whose value should be returned (null for the entire object)
        Returns:
        The attribute value
      • otherProduct

        Object otherProduct​(String parameterName,
                            String attributeName,
                            String filterFormulaName,
                            Object filterFormulaParam)
        Triggers a custom-named product picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        attributeName - The attribute whose value should be returned (null for the entire object)
        filterFormulaName - Unique name of a formula that will be triggered when the Product picker opens
        filterFormulaParam - Additional data for filterFormula
        Returns:
        The attribute value
      • otherProduct

        Object otherProduct​(String parameterName)
        Triggers a custom-named product picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        Returns:
        The product object
      • productExtension

        Object productExtension​(String extensionName)
        Retrieves a list of rows from a Product Extension (PX) table named extensionName for the SKU being calculated (sku in the context).

        Performance Considerations: Consider use of getBatchInfo() for the performance reasons.

        Example:

         def promotions = api.productExtension("Promotion")
         def promotionSize = promotions?.getAt(0)
         
        Parameters:
        extensionName - The name of the Product Extension table to read data from.
        Returns:
        List of PX rows/records (represented as a Map), so it returns List of Maps.
        See Also:
        getBatchInfo(), productExtension(String, Filter...)
      • productExtension

        Object productExtension​(String extensionName,
                                Filter... filters)
        Retrieves a list of rows from a Product Extension (PX) table named extensionName for the SKU being calculated (sku in the context) additionally filtered by filters.

        Performance Considerations: Consider use of getBatchInfo() for the performance reasons.

        Example:

         def filter = [
                 Filter.greaterOrEqual("ValidFrom", targetDate),   // or Filter.greaterOrEqual("attribute1", targetDate)
                 Filter.lessOrEqual("ValidTo", targetDate)       // Filter.lessOrEqual("attribute2", targetDate)
         ]
        
         def promotions = api.productExtension("Promotion", *filter)
         def promotion = promotions?.getAt(0)
         
        Parameters:
        extensionName - The name of the product extension table
        filters - One or more Filter objects that narrow down the search
        Returns:
        List of matching PX rows/records (represented as a Map), so it returns List of Maps.
        See Also:
        getBatchInfo(), productExtension(String)
      • productCompetition

        Object productCompetition()
        Retrieves a list of all product competition rows/records (PCOMP) for the SKU being calculated (sku in the context). Consider using productExtension(String) instead since that gives you a better flexibility.
        Returns:
        List of PCOMP records (represented as a Map)
        See Also:
        getBatchInfo()
      • productCompetition

        Object productCompetition​(Filter... filters)
        Retrieves a list of product competition rows/records (PCOMP) for the SKU being calculated (sku in the context) filtered by filters. Consider using productExtension(String) instead since that gives you a better flexibility.
        Parameters:
        filters - One or more Filter objects that narrow down the search
        Returns:
        List of matching PX records (represented as a Map)
      • productXRef

        Object productXRef()
        Retrieves a list of all product reference records (PXREF) for the SKU being calculated. Consider use of getBatchInfo() for the performance reasons.
        Returns:
        List of PXREF records (represented as a Map)
        See Also:
        getBatchInfo()
      • rebateAgreementUserEntry

        Object rebateAgreementUserEntry​(String parameterName,
                                        String attributeName)
        Prompts the user to input parameters for a rebate agreement (RBA).
        Parameters:
        parameterName - - The name of an entry in the input parameters listing (mandatory)
        attributeName - - The name of the attribute you need (mandatory)
        Returns:
        The attribute of the rebate agreement or null if RA does not exists
      • productXRef

        Object productXRef​(Filter... filters)
        Retrieves a list of all product reference records (PXREF) for the SKU being calculated.
        Parameters:
        filters - One or more Filter objects that narrow down the PXREF search
        Returns:
        List of matching PXREF records (represented as a Map)
        See Also:
        getBatchInfo()
      • customer

        Object customer​(String attributeName)
        Retrieves the given attribute value from the Customers table for the customer selected by user in the input parameter "Customer". The customer object is cached and the next call reads the value from cached record.

        Note: the value of the Customer input parameter can be also inherited from the parent - for example, if the user selects the Customer on the Quote header, then such input value is available also during the Quote Line calculation.

        Important Side effect: During the Syntax Check mode, this functions triggers creation of the input parameter Customer. This influence you, for example, on the Quote line item, where you might need to read certain customer attribute value, but maybe not create the Customer picker. In that case you must avoid running this function call during the Syntax Check mode.

        Parameters:
        attributeName - The attribute value to be returned. Can be either the real column name (like customerId, name, attribute1) or also the name given in the Rename and Customize column dialog.
        Returns:
        The value of the attribute
      • customer

        Object customer​(String attributeName,
                        boolean defaultFromParent)
        Equivalent of the standard syntax "Customer" function. Retrieves the given attribute value of the customer context parameter. If the value is null and defaultFromParent is true, it retrieves (and returns) the value from the customer's parent regardless if that value is null as well or not. If there is no parent customer set, null will be returned.
        Parameters:
        attributeName - The attribute value to be returned
        defaultFromParent - Determines whether to look up the value from the parent customer (if any) in case it is null in the customer
        Returns:
        The value of the attribute
      • customer

        Object customer​(String attributeName,
                        String customerId)
        Retrieves the given attribute value from the Customers table for the given customer. The customer object is cached and the next call reads the value from the cached record.
        Parameters:
        attributeName - The attribute value to be returned. Can be either the real column name (like customerId, name, attribute1) or also the name given in the Rename and Customize column dialog.
        customerId - The customerId value to be looked up in the Customers table
        Returns:
        The value of the attribute (or null if no customer found)
      • customer

        Object customer​(String attributeName,
                        String customerId,
                        boolean defaultFromParent)
        Retrieves the given attribute value of the given customer. If the value is null and defaultFromParent is true, it retrieves (and returns) the value from the customer's parent regardless if that value is null as well or not. If there is no parent customer set, null will be returned.
        Parameters:
        attributeName - The attribute value to be returned
        customerId - The customerId value for the customer search
        defaultFromParent - Determines whether to look up the value from the parent customer (if any) in case it is null in the customer
        Returns:
        The value of the attribute (or null if no customer found)
      • customer

        Object customer​(String attributeName,
                        String customerId,
                        boolean defaultFromParent,
                        String filterFormulaName,
                        Object filterFormulaParam)
        Retrieves a named attribute value of the named customer (if the value is null and defaultFromParent is true, retrieves (and returns) the value from the customer's parent regardless if that value is null as well or not. If there is no parent customer set, null will be returned)
        Parameters:
        attributeName - The attribute value to be returned
        customerId - The customerId value for the customer search
        defaultFromParent - Determines whether to look up the value from the parent customer (if any) in case it is null in the customer
        filterFormulaName - Unique name of a formula that will be triggered when the Customer picker opens
        filterFormulaParam - Additional data for filterFormula (e.g. agreement's typedId,...)
        Returns:
        The value of the attribute (or null if no customer found)
      • otherCustomer

        Object otherCustomer​(String parameterName)
        Triggers a custom-named customer picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        Returns:
        The customer object
      • otherCustomer

        Object otherCustomer​(String parameterName,
                             String attributeName)
        Triggers a custom-named customer picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        attributeName - The attribute which value to return (null for the entire object)
        Returns:
        The attribute value
      • otherCustomer

        Object otherCustomer​(String parameterName,
                             String attributeName,
                             boolean defaultFromParent)
        Triggers a custom-named customer picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        attributeName - The attribute whose value should be returned (null for the entire object)
        defaultFromParent - Determines whether to look up the attribute value from the parent customer (if any) in case it is null in the customer
        Returns:
        The attribute value
      • otherCustomer

        Object otherCustomer​(String parameterName,
                             String attributeName,
                             boolean defaultFromParent,
                             String filterFormulaName,
                             Object filterFormulaParam)
        Triggers a custom-named customer picker input parameter.
        Parameters:
        parameterName - The name of the parameter
        attributeName - The attribute whose value should be returned (null for the entire object)
        defaultFromParent - Determines whether to look up the attribute value from the parent customer (if any) in case it is null in the customer
        filterFormulaName - Unique name of a formula that will be triggered when the Customer picker opens
        filterFormulaParam - Additional data for filterFormula (e.g. agreement's typedId,...)
        Returns:
        The attribute value
      • customerExtension

        Object customerExtension​(String extensionName,
                                 Filter... filters)
        Retrieves a list of all customer extentions records (CX) from a CX table named extensionName

        Example:

         def filter = Filter.equal("attribute1", "ShipTo")   // Type
        
         def addresses = api.customerExtension("Addresses", filter)
        
         if (addresses) {
             def address = addresses.getAt(0)
             ...
         }
         
        Parameters:
        extensionName - The name of the extension
        filters - None, one or more Filter object that narrow down the CX search
        Returns:
        List of matching CX records (represented as a Map)
      • getCalculableLineItem

        <T extends CalculableLineItem> T getCalculableLineItem​(Object clic,
                                                               String lineId)
        Returns a line item of the given calculable line item collection (CLIC). Currently, there are three types of CLICs: Quote, Contract and Rebate Agreement.
        Type Parameters:
        T - ContractLineItem (CTLI), QuoteLineItem (QLI) or RebateAgreementLineItem (RBALI)
        Parameters:
        clic - The CLIC to which the line item belongs, it may either be the CLIC object as such (its map representation to be exact) or typedId or a uniqueName.
        lineId - The lineId of the line item
        Returns:
        The calculable line item
      • getCalculableLineItemResult

        Object getCalculableLineItemResult​(Object cli,
                                           String... resultNamesOrLabels)
        Returns results of the given names (or labels) from a line item object (its map representation).

        Note: The line item object will typically be fetched via getCalculableLineItem(Object, String).

        Parameters:
        cli - The calculable line item
        resultNamesOrLabels - The result names or labels
        Returns:
        Either a single result or a map(nameOrLabel,result) of results if there were more names (labels) specified
      • getCalculableLineItemCollection

        Object getCalculableLineItemCollection​(String typedId)
        Returns the full object (header and line items) of e.g. a quote, rebate agreement or contract.
        Parameters:
        typedId - The typeId of the object
        Returns:
        A map specifying the line item collection or null if an invalid typedId was passed
      • createNewRevision

        Object createNewRevision​(String typedId)
        Creates a revision of CalculableLineItemCollection (Quote, Rebate Agreement, Contract).
        Parameters:
        typedId - The typeId of the object
        Returns:
        A map specifying the revised line item collection or null if an invalid typedId was passed
      • addWarning

        void addWarning​(String message)
        Adds a warning to the logic/formula execution warning log. Warning usually explains to the user, that there was a "technical" problem (e.g. missing data, inputs) and the calculation could not be completed.

        The warnings are displayed:

        • for Quotes, Rebates, Contracts - in "Calculation Results" section for the line items. The Warning is shown next to the element, in which it was added, but if the element is not visible, then it will appear together with the next visible element.
        • for Pricelists, Pricegrids, Datamarts, Policy records - all warnings from all elements are listed together in a special "Warnings" column in the grid list items

        Example:

         def cost = ...
        
         if (cost == null) {
              api.addWarning("Cannot calculate the List Price because of missing cost")
              return null
         }
         
        Parameters:
        message - The warning text message
      • contextByLabel

        Object contextByLabel​(String label)
        Retrieves the previous calculation result by the logic element label (not the element result name).
        Parameters:
        label - The logic element label
        Returns:
        The calculation result of that element
      • vLookup

        Object vLookup​(String parameterName)
        Searches for a record in the price parameter table named parameterName where the column 'name' matches the value entered by the user (in a dropdown input parameter) and returns the value from the column 'value'.

        Side-effect: during the Syntax Check mode this function creates a new input parameter (dropdown) whose values are taken from the column "name" of the given Price Parameter.

        Parameters:
        parameterName - The name of the price parameter table to lookup
        Returns:
        For Simple price parameter, it returns the value of the "value" column from the found row. In case of matrix lookups the entire object/row.
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       Object attributeNameOrKeyOrRangeValue)
        Searches for a record in the price parameter table named parameterName where the column 'name' (for LTV or MLTV) or 'key1' (for MLTV2-6) matches the attributeNameOrKeyOrRangeValue value and returns the value from the column 'value' (LTV) or 'attribute1' (MLTV). Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from the cache.

        Example:

         def productGroup = api.product("ProductGroup")  // or "attribute2"
         def shippingCost = api.vLookup("ShippingCosts", productGroup)
         
        Parameters:
        parameterName - The name of the price parameter table
        attributeNameOrKeyOrRangeValue - A predefined key or range value or in case of a matrix lookup a user entry
        Returns:
        The value of the column 'value' for SIMPLE (LTV) or 'attribute1' for MATRIX (MLTV)
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       String key)
        This syntax is only relevant for MATRIX 1-key price parameter tables (MLTV). The function searches for a record in the price parameter table named parameterName where the column 'key1' matches the key1 parameter and returns the value of the column attributeName. Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from cache.

        Example:

         def prevailing = api.vLookup("Manufacturer", "attribute1", "Meat company")
         
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        key - The key of the parameter table
        Returns:
        The value of the column attributeName or full object if attribute name is null
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       String key1,
                       String key2)
        This syntax is only relevant for MATRIX 2-key price parameter tables (MLTV2). The function searches for a record in a price parameter table named parameterName where the columns 'key1'-'key2' match the key1-key2 parameters and returns the value from the column attributeName. Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from the cache.

        Example:

         def exchangeRate = api.vLookup("ExchangeRate", "attribute1", "EUR", "USD")
         
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        key1 - The key1 of the parameter table
        key2 - The key2 of the parameter table
        Returns:
        The value of the column attributeName or full object if attribute name is null
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       String key1,
                       String key2,
                       String key3)
        This syntax is only relevant for MATRIX 3-key price parameter tables (MLTV3). The function searches for a record in the price parameter table named parameterName where the columns 'key1'-'key3' match the key1-key3 parameters and returns the value from the column attributeName. Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from the cache.

        Example:

         def exchangeRate = api.vLookup("ExchangeRate", "attribute1", "EUR", "USD", "2018")
         
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        key1 - The key1 of the parameter table
        key2 - The key2 of the parameter table
        key3 - The key3 of the parameter table
        Returns:
        The value of the column attributeName or full object if attribute name is null
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       String key1,
                       String key2,
                       String key3,
                       String key4)
        This syntax is only relevant for MATRIX 4-key price parameter tables (MLTV4). The function searches for a record in the price parameter table named parameterName where the columns 'key1'-'key4' match the key1-key4 parameters and returns the value from the column attributeName. Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from the cache.
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        key1 - The key1 of the parameter table
        key2 - The key2 of the parameter table
        key3 - The key3 of the parameter table
        key4 - The key4 of the parameter table
        Returns:
        The value of the column attributeName or full object if attribute name is null
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       String key1,
                       String key2,
                       String key3,
                       String key4,
                       String key5)
        This syntax is only relevant for MATRIX 5-key price parameter tables (MLTV5). The function searches for a record in the price parameter table named parameterName where the columns 'key1'-'key5' match the key1-key5 parameters and returns the value from the column attributeName. Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from the cache.
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        key1 - The key1 of the parameter table
        key2 - The key2 of the parameter table
        key3 - The key3 of the parameter table
        key4 - The key4 of the parameter table
        key5 - The key5 of the parameter table
        Returns:
        The value of the column attributeName or full object if attribute name is null
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       String key1,
                       String key2,
                       String key3,
                       String key4,
                       String key5,
                       String key6)
        This syntax is only relevant for MATRIX 6-key price parameter tables (MLTV6). The function searches for a record in the price parameter table named parameterName where the columns 'key1'-'key6' match the key1-key6 parameters and returns the value from the column attributeName. Once the record is found, it remains cached during the whole calculation and the next call for the same arguments reads the value from the cache.
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        key1 - The key1 of the parameter table
        key2 - The key2 of the parameter table
        key3 - The key3 of the parameter table
        key4 - The key4 of the parameter table
        key5 - The key5 of the parameter table
        key6 - The key6 of the parameter table
        Returns:
        The value of the column attributeName or full object if attribute name is null
        See Also:
        findLookupTableValues(String, Filter...)
      • vLookup

        Object vLookup​(String parameterName,
                       String attributeName,
                       Map keys)
        This syntax can be applied to all MATRIX lookup types. Essentially the keys are passed in a map. The key name can be the technical name ("key1", etc) or the meta-renamed name.

        Example:

         def keys = [
                 "Country": country,
                 "DeliveryType": input.DeliveryType
         ]
        
         return api.vLookup("FreightSurcharge", "FreightSurcharge", keys)
         
        Parameters:
        parameterName - The name of the price parameter table
        attributeName - The name of the attribute to retrieve, or a comma separated list of attributes
        keys - A map with the keys of the row to retrieve. Note: All keys need to be present for the table in question!
        Returns:
        A map with value of the columns of attributeNames as keys or full object if attributeNames is null
      • vLookup

        Map<String,​Object> vLookup​(String parameterName,
                                         List<String> attributeNames,
                                         Map keys)
        This syntax can be applied to all MATRIX lookup types. Essentially the keys are passed in a map. The key name can be the technical name ("key1", etc) or the meta-renamed name.
        Parameters:
        parameterName - The name of the price parameter table
        attributeNames - The names of the attribute to retrieve
        keys - A map with the keys of the row to retrieve. Note: All keys need to be present for the table in question!
        Returns:
        A map with value of the columns of attributeNames as keys or full object if attributeNames is null
      • decimalUserEntry

        Object decimalUserEntry​(String entryName)
        Creates an input parameter that lets the user enter a decimal value. Rendered as a numeric field.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        Decimal value entered by the user as a BigDecimal
        See Also:
        integerUserEntry(String)
      • integerUserEntry

        Object integerUserEntry​(String entryName)
        Returns integer numeric value entered by the user in the input parameter.

        Side-effect: during the Syntax Check mode, this function triggers creation of the input parameter, that lets the user enter an integer value. The input is rendered as a numeric field.

        Parameters:
        entryName - The name of the user input parameter. Use "camel case" for the names (no spaces). This value is not meant as a label of the input field, but rather a name, which should stay stable in a long time period - remember, the input fields are stored e.g. on every single Quote line item and are created only once, when adding the new line. If you need to modify the label (or other properties) of the input parameter, you can use getParameter(String)
        Returns:
        Integer value entered by the user as a BigDecimal
        See Also:
        decimalUserEntry(String), userEntry(String)
      • stringUserEntry

        Object stringUserEntry​(String entryName)
        Returns text value entered by the user in the input parameter.

        Side-effect: during the Syntax Check mode, this function triggers creation of the single-text input parameter.

        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        Text value entered by the user as a String
        See Also:
        textUserEntry(String)
      • stringUserEntry

        Object stringUserEntry​(String entryName,
                               String textMask)
        Creates an input parameter that lets the user enter a short text value. Rendered as a single-line text field.
        Parameters:
        entryName - The name of the user entry parameter
        textMask - Optional text mask that is displayed in the UI
        Returns:
        Text value entered by the user as a String
        See Also:
        textUserEntry(String)
      • stringUserEntry

        Object stringUserEntry​(String entryName,
                               String textMask,
                               String label)
        Creates an input parameter that lets the user enter a short text value. Rendered as single-line text field.
        Parameters:
        entryName - The name of the user entry parameter
        textMask - Optional text mask that is displayed in the UI
        label - Label of the entry box
        Returns:
        Text value entered by the user as String
        See Also:
        textUserEntry(String, String)
      • textUserEntry

        Object textUserEntry​(String entryName)
        Creates an input parameter that lets the user enter a longer text value. Rendered as a multi-line text box.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        Text value entered by the user as a String
        See Also:
        stringUserEntry(String)
      • textUserEntry

        Object textUserEntry​(String entryName,
                             String label)
        Creates an input parameter that lets the user enter a longer text value. Rendered as a multi-line text box.
        Parameters:
        entryName - The name of the user entry parameter
        label - The label of the entry box
        Returns:
        Text value entered by the user as a String
        See Also:
        stringUserEntry(String, String, String)
      • booleanUserEntry

        Object booleanUserEntry​(String entryName)
        Creates an input parameter that lets the user enter a boolean (yes or no) value. Rendered as a checkbox.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        The boolean value entered by the user
      • dateTimeUserEntry

        Object dateTimeUserEntry​(String entryName)
        Creates an input parameter that lets the user to enter a date time value in format "dd/MM/yyyy HH:mm" (e.g. "23/01/2019 10:30").

        Rendered as a datetime picker field.

        Important: The format implicitly uses the GMT/UTC time zone and so the returned value may differ from what was entered in on the client (as the client time may be in a different time zone).

        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        String value entered by the user in the format "yyyy-MM-dd'T'HH:mm:ss"

        See Also:
        parseDate(String, String)
      • productGroupEntry

        Object productGroupEntry​(String... entryName)
        Creates an input parameter that lets the user select a group of products and returns the selection as a Map. This is commonly used in PromotionManager and RebateManager. It is rendered as a product group picker widget.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        The entered product group as a Map
         [
           "productFieldName"  : "attribute3",
           "productFieldLabel" : "Business Unit",
           "productFieldValue" : "MeatBall"
         ]
         
      • datamartProductGroupEntry

        Object datamartProductGroupEntry​(String... entryName)
        Creates an input parameter that lets the user select a group of products and returns the selection as a Map. This is commonly used in PromotionManager and RebateManager. It is rendered as a product group picker widget. Only PA searchable Product Extensions will be available.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        The entered product group as a Map
         [
           "productFieldName"  : "attribute3",
           "productFieldLabel" : "Business Unit",
           "productFieldValue" : "MeatBall"
         ]
         
      • productGroupEntry

        Object productGroupEntry​(String entryName,
                                 String filterFormulaName,
                                 Object filterFormulaParam)
        Creates an input parameter that lets the user select a group of products and returns the selection as a Map. This is commonly used in PromotionManager and RebateManager. It is rendered as a product group picker widget.
        Parameters:
        entryName - The name of the user entry parameter
        filterFormulaName - A unique name of a formula that will be triggered when the customer picker opens
        filterFormulaParam - Additional data for filterFormula
        Returns:
        The entered product group as a Map
         [
           "productFieldName"  : "attribute3",
           "productFieldLabel" : "Business Unit",
           "productFieldValue" : "MeatBall"
         ]
         
      • customerGroupEntry

        Object customerGroupEntry​(String... entryName)
        Creates an input parameter that lets the user select a group of customers and returns the selection as a Map. This is commonly used in PromotionManager and RebateManager. It is rendered as a customer group picker widget.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        The entered customer group as a Map
         [
           "customerFieldName" : "attribute3",
           "customerFieldLabel" : "Customer Type",
           "customerFieldValue" : "Restaurant"
         ]
         
        See Also:
        productGroupEntry(String...)
      • datamartCustomerGroupEntry

        Object datamartCustomerGroupEntry​(String... entryName)
        Creates an input parameter that lets the user select a group of customers and returns the selection as a Map. This is commonly used in PromotionManager and RebateManager. It is rendered as a customer group picker widget. Only PA searchable Customer Extensions will be available.
        Parameters:
        entryName - The name of the user entry parameter
        Returns:
        The entered customer group as a Map
         [
           "customerFieldName" : "attribute3",
           "customerFieldLabel" : "Customer Type",
           "customerFieldValue" : "Restaurant"
         ]
         
        See Also:
        productGroupEntry(String...)
      • customerGroupEntry

        Object customerGroupEntry​(String entryName,
                                  String filterFormulaName,
                                  Object filterFormulaParam)
        Creates an input parameter that lets the user select a group of customers and returns the selection as a Map. This is commonly used in PromotionManager and RebateManager. It is rendered as a customer group picker widget.
        Parameters:
        entryName - The name of the user entry parameter
        filterFormulaName - A unique name of a formula that will be triggered when the customer picker opens
        filterFormulaParam - Additional data for filterFormula (e.g. agreement's typedId,...)
        Returns:
        The entered customer group as a Map
         [
           "customerFieldName" : "attribute3",
           "customerFieldLabel" : "Customer Type",
           "customerFieldValue" : "Restaurant"
         ]
         
        See Also:
        productGroupEntry(String...)
      • multiTierEntry

        Object multiTierEntry​(String entryName,
                              String... arguments)
        Creates an input parameter that lets the user enter multiple discounts/surcharges/tiers by amount. This is commonly used in PromotionManager and RebateManager. It is rendered as a multi tier entry widget. Every line holds an amount and the given discount/surcharge in an ascending or descending order.
        Parameters:
        entryName - The name of the user entry parameter
        arguments - Two value hints: sort type (can be either "ASC" which is the default or "DESC") and order validation type (can be "VALIDATE" or "NO_VALIDATION").
        Returns:
        The values entered by the user as a TieredValue object
      • option

        Object option​(String entryName,
                      Object... options)
        Returns value selected by the user from a list displayed in drop-down input parameter.

        Side-effect: during the Syntax Check mode, this function triggers creation of the drop-down input parameter with the given list of options.

        Example 1:

         return api.option("Currency", ["EUR", "USD"])
         

        Example 2:

         def salesOrgs = api.findLookupTableValues("SalesOrg").collect{
           it.name
         }
        
         return api.option("SalesOrg", salesOrgs)
         
        Parameters:
        entryName - The name of the user entry parameter
        options - An arbitrary number of options that should be displayed in the drop down list
        Returns:
        The value selected by the user. During Syntax Check execution mode, it returns mock data.
        See Also:
        options(String, Object...)
      • option

        Object option​(String entryName,
                      List<Object> options,
                      Map<String,​Object> labels)
        Creates an input parameter that lets the user select a single value from the predefined options. It is rendered as a drop down list of possible options. You can add custom (display-only) labels.

        Example:

         def salesOrgMap = api.findLookupTableValues("SalesOrg").collectEntries{
           [(it.name) : it.name]
         }
        
         return api.option("SalesOrg", salesOrgMap.keySet() as List, salesOrgMap)
         
        Parameters:
        entryName - The name of the user entry parameter
        options - An arbitrary number of options that should be displayed in the drop down list
        labels - A map [value : label] of labels that should be shown in the UI. If null or empty will behave same as api.option() without a label definition.
        Returns:
        The user entered value
        See Also:
        options(String, List, Map)
      • options

        Object options​(String entryName,
                       Object... options)
        Creates an input parameter that lets the user select multiple values from the predefined options. It is rendered as a drop down list of possible options. Each selected value appears at the top.
        Parameters:
        entryName - The name of the user entry parameter
        options - An arbitrary number of options that should be displayed in the drop down list
        Returns:
        List of user selected values
        See Also:
        option(String, Object...)
      • options

        Object options​(String entryName,
                       List<Object> options,
                       Map<String,​Object> labels)
        Creates an input parameter that lets the user select multiple values from the predefined options. It is rendered as a drop down list of possible options. Each selected value appears at the top. You can add custom (display-only) labels.
        Parameters:
        entryName - The name of the user entry parameter
        options - An arbitrary number of options that should be displayed in the drop down list
        labels - A map [value : label] of labels that should be shown in the UI. If null or empty will behave same as option(String, Object...) without a label definition.
        Returns:
        List of user selected values
      • filterBuilderUserEntry

        Object filterBuilderUserEntry​(String entryName,
                                      String typeCode)
        Creates an input parameter that lets the user build a filter for a table of objects of the type defined by typeCode parameter.

        It is rendered as a filter builder widget allowing to construct a filter (e.g. to define filter for Products, set the typeCode to P).

        The filter object can be used in other functions, like find(String, Filter...), stream(String, String, Filter...) count(String, Filter...) etc.

        Parameters:
        entryName - The name of the user entry parameter
        typeCode - A type code string of the type of the object for which the filter is set. The supported type codes currently are "P" (Product data) and "C" (Customer data).
        Returns:
        A filter object defined by the user
      • datamartFilterBuilderUserEntry

        Object datamartFilterBuilderUserEntry​(String entryName,
                                              String source,
                                              Object... args)
        Creates an input parameter that lets the user build a filter for a given Datamart.

        The filter can be used in DatamartContext.Query.where(Filter...) of the datamartQuery(Object...).

        It will render a FilterBuilder widget entry allowing to construct a filter object filtering on the specified Data Source.

        Example:

         def filter1 = datamartFilterBuilderUserEntry("ProductGroup", "Transactions_DM")
        
         def dimFilterList = ["CustomerId", "ProductId"]
         def filter2 = datamartFilterBuilderUserEntry("ProductGroup", "Transactions_DM", dimFilterList)
        
         def dimFilterMap = ["CustomerId" : "CD-00155", "ProductId" : "MB-0005"]
         def filter3 = datamartFilterBuilderUserEntry("ProductGroup", "Transactions_DM", dimFilterMap, Filter.equal("Country", "DE"))
         
        Parameters:
        entryName - The name of the user entry parameter
        source - The name of the source for which the filter is set. The resolution of the source is as follows:
        1. any Datamart - by typedId, sourceName, uniqueName or label (uniqueName and label for backwards compatibility)
        2. any FieldCollection - by typedId or sourceName
        args - There can be up to 2 arguments: one can be a Map or List and the other a Filter. The order does not matter. If the argument is a Map, each pair [fieldName : value] will be used as a filter.
        Returns:
        A filter object to the given source
      • pricelist

        Object pricelist​(String listName)
        Looks up the result price (considering a manual override) of an SKU being calculated (SKU in the context) in a price list of the given name. The price list line has to be approved and the targetDate of the price list has to be on or prior to the calculation targetDate. If multiple price lists are found, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list to be searched
        Returns:
        The resultPrice of the price list record for the SKU
      • pricelist

        Object pricelist​(String listName,
                         String attributeName)
        Looks up the value of attribute given by attributeName (considering a manual override) of an SKU being calculated (SKU in the context) in a price list of the given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If multiple price lists are found, the one with the targetDate closer to the calculation targetDate is used.
        Parameters:
        listName - The name of the price list
        attributeName - The name of the attribute to retrieve
        Returns:
        The value of the attributeName column of the price list record
        See Also:
        pricelistItem(String, String)
      • pricelist

        Object pricelist​(String listName,
                         String attributeName,
                         String sku)
        Looks up the result price (considering a manual override) of a given SKU in a price list of the given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If there are multiple price lists of the same name, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list
        attributeName - The name of the attribute to retrieve
        sku - The SKU to use
        Returns:
        The value of the attributeName column of the price list record
        See Also:
        pricelistItem(String, String)
      • pricelist

        Object pricelist​(String listName,
                         String attributeName,
                         String sku,
                         String key2)
        Looks up the attribute defined by attributeName (considering a manual override) of the given SKU in a matrix price list of the given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If there are multiple price lists of the same name, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list
        attributeName - The name of the attribute to retrieve
        sku - The SKU to use
        key2 - The key2 to use
        Returns:
        The value of the attributeName column of the matrix price list record
        See Also:
        pricelistItem(String, String, String)
      • pricelistItem

        Object pricelistItem​(String listName)
        Looks up the price list item record (PLI or XPLI) of an SKU being calculated in a price list of the given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If there are multiple price lists of the same name, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list
        Returns:
        The entire price list item record (PLI or XPLI)
        See Also:
        pricelist(String)
      • pricelistItem

        Object pricelistItem​(String listName,
                             String sku)
        Looks up the price list item record (PLI) of the given SKU in a price list of a given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If there are multiple price lists of the same name, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list
        sku - The SKU to use
        Returns:
        The entire price list item record (PLI)
        See Also:
        pricelist(String, String, String)
      • pricelistItem

        Object pricelistItem​(String listName,
                             String sku,
                             String key2)
        Looks up the matrix price list item record (XPLI) of the given SKU in a matrix price list of the given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If there are multiple price lists of the same name, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list
        sku - The SKU to use
        key2 - The key2 to use
        Returns:
        The entire matrix price list item record (XPLI)
        See Also:
        pricelist(String, String, String, String)
      • pricelistItem

        Object pricelistItem​(String listName,
                             String sku,
                             String key2,
                             Date targetDate)
        Looks up the matrix price list item record (XPLI) of the given SKU in a matrix price list of the given name. The price list line has to be approved and the targetDate of the price list has to be prior to the calculation targetDate. If there are multiple price lists of the same name, the one with the targetDate closer to the calculation targetDate is chosen.
        Parameters:
        listName - The name of the price list
        sku - The SKU to use
        key2 - The key2 to use
        targetDate - The targetDate for teh search
        Returns:
        The entire matrix price list item record (XPLI)
        See Also:
        pricelist(String, String, String, String)
      • getPricelistItem

        Map<String,​Object> getPricelistItem​(String listName)
        Similar to the pricelistItem(String) function. However, it optimizes the subsequent processing by providing the results as a map directly.
        Parameters:
        listName - The name of the price list. Target date and SKU matching applies.
        Returns:
        The price list object
        See Also:
        pricelistItem(String)
      • bom

        Object bom()
        Accesses and retrieves values from a rolled-up bill of materials for the SKU being calculated. All quantities are rolled up and summed.
        Returns:
        A list with the summed up quantities
      • bom

        Object bom​(String lookupTableName)
        Accesses and retrieves values from a rolled-up bill of materials for the SKU being calculated. The summed up quantities are multiplied with a factor that is retrieved by a lookup by the material name from the provided parameter. Example: material-cost table
        Parameters:
        lookupTableName - The parameter table name
        Returns:
        A list with the summed up and multiplied quantities
      • bom

        Object bom​(String lookupTableName,
                   String categoryName)
        Accesses and retrieves values from a rolled-up bill of materials for the SKU being calculated. Only BoM records with the specified category are considered. The summed up quantities are multiplied with a factor that is retrieved by a lookup by the material name from the provided parameter. Example: material-cost table
        Parameters:
        lookupTableName - The parameter table name
        categoryName - The category name to filter on
        Returns:
        A list with the summed up and multiplied quantities
      • bom

        Object bom​(String lookupTableName,
                   String categoryName,
                   String materialName)
        Accesses and retrieves the values from a rolled-up bill of materials for the SKU being calculated Only BoM records with the specified category and the material are considered. The summed up quantities are multiplied with a factor that is retrieved by a lookup by the material name from the provided parameter. An example would be a material-cost table.
        Parameters:
        lookupTableName - The parameter table name
        categoryName - The category name to filter on
        materialName - The material to filter on
        Returns:
        A list with the summed up and multiplied quantities
      • bomList

        Object bomList()
        Rolls up the current SKU's BoM and returns the rolled up BoM records (not just the quantities).
        Returns:
        A list of BoM records
      • anyUser

        Object anyUser​(String entryName)
        Creates an input parameter that lets the user select a user from the list of all users. It is rendered as a user picker dialog / select list.
        Parameters:
        entryName - The name of the entry parameter
        Returns:
        The login name of the selected user or null
      • user

        Object user​(String attributeName)
        Returns a value from the current user's master data.

        Example:

         // retrieves the email of the user
         def email = api.user("email")
         
        Parameters:
        attributeName - The attribute to return
        Returns:
        The user's attribute value
      • user

        Object user()
        Returns the entire master data object of the current user.

        Example:

         // retrieves the email of the user
         def email = api.user()?.email
         
        Returns:
        The user object (U)
      • input

        Object input​(String inputName)
        Retrieves the value of the input parameter of the given name. It only reads the value, it does not trigger rendering any input widget (i.e. no side-effects)
        Parameters:
        inputName - The input parameter name
        Returns:
        The value entered by the user in the input parameter. During Syntax Check execution mode it returns mock data.
        See Also:
        userEntry(String)
      • inputMatrix

        Object inputMatrix​(String inputMatrixName,
                           String... columnNames)
        Creates an input parameter that lets the user select a matrix of values. It renders as a grid-style input widget with the specified columns. The result will be a list (= the rows) of maps (= the row's columns). The map attribute names are the column names. Make sure the column names are valid JSON identifiers (spaces are ok but try to avoid special chars).
        Parameters:
        inputMatrixName - The name of the parameter
        columnNames - The column names/labels
        Returns:
        A list (=the rows) of maps (=the row's columns)
      • inputMatrix

        Object inputMatrix​(String inputMatrixName,
                           Map<String,​Object> paramConfig,
                           String... columns)
        Creates an input parameter that lets the user select a matrix of values. It renders as a grid-style input widget with the specified columns. The result will be a list (=the rows) of maps (=the row's columns). The map attribute names are the column names. Make sure the column names are valid JSON identifiers (spaces are ok but try to avoid special chars).
        Parameters:
        inputMatrixName - The name of the parameter
        paramConfig - Map of configuration settings with the following options (key, value):
        • 'canModifyRows': false/true (the user can add and delete a row)
        • 'readOnlyColumns': List of columns (names) to be uneditable
        • 'noCellRefresh': false/true (do not update Configurator on each edit)
        • 'defaultHeight': number which specifies default table height
        • 'fixTableHeight': false/true (preserve default height of table)
        • 'fitFieldWidths': false/true (Should fields autofit their widths to titles or content?)
        columns - The column names/labels
        Returns:
        A list (=the rows) of maps (=the row's columns)
      • parsableInputFile

        Object parsableInputFile​(String inputName)
        Creates an input parameter that lets the user pick a file. It renders as a file input widget that allows to use data from a XLSX file in a logic.
        Parameters:
        inputName - The name of the parameter
        Returns:
        A handle that uniquely identifies the binary and its version that was assigned to the input
      • parsableInputFileData

        Object parsableInputFileData​(String inputName)
        If a parsableInputFile has a value, this function opens the file and parses it to basic Groovy data structures.
        Parameters:
        inputName - The name of the parameter
        Returns:
        [data: [sheetName: [row1col1, row1col2, ...], [row2col1, row2col2, ...], ...]
      • parsableInputFileDataFromHandle

        Object parsableInputFileDataFromHandle​(String fileHandle)
        If a parsableInputFile has a value, this function opens the file and parses it to basic groovy datastructures.
        Parameters:
        fileHandle - The value of the parameter
        Returns:
        [data: [sheetName: [row1col1, row1col2, ...], [row2col1, row2col2, ...], ...]
      • filter

        Object filter​(String property,
                      Object value)
        Deprecated.
        Creates a filter object that can be used in other API functions. The operator is always "equals", i.e. property = value.

        Example:

         def cas = api.find("CA",
                        api.filter("assignmentId", mplId),
                        api.filter("assignmentType", "MPL")
         )
         
        Parameters:
        property - The name of the property to filter on
        value - The specified value
        Returns:
        A filter object
      • filterFromMap

        Filter filterFromMap​(Map<String,​Object> filterMap)
        Constructs a Filter object from the map representation of that filter (from the "wire format"). The map representation is the way the filter is described in the JSON requests between the UI and the server.
        Parameters:
        filterMap - The filter in the form of nested maps
        Returns:
        The filter object
      • customerToRelatedObjectsFilter

        Filter customerToRelatedObjectsFilter​(String relatedObjectTypeCode,
                                              String customerId)
        Creates a filter to be applied to a search on a related object type, limiting the result to objects of the related type that have a link to the given customer.

        Example:

                        def filter = api.customerToRelatedObjectsFilter("RBA", "104083")        // customerId=104083
                        def rbas = api.find("RBA", 0, 0, null, filter)
                        api.trace("rbas for customer #104083", null, rbas)
         
        Parameters:
        relatedObjectTypeCode - TypeCode of the related object type. The possible values are:
        • 'PR': PriceRecord
        • 'CT': Contract
        • 'CTLI': ContractLineItem
        • 'RBA': RebateAgreement
        • 'RBALI': RebateAgreementLineItem
        customerId - Customer.id to filter on
        Returns:
        A filter object
      • relatedObjectToCustomersFilter

        Filter relatedObjectToCustomersFilter​(String relatedObjectTypedId)
        Creates a filter to be applied to a customer search, limiting the result to customers that are linked to the given related object, the latter defined by its typedId.

        Example:

         def ras = api.find("RBA", 0, 1, null, null)
         ras.each {
                        def filter = api.relatedObjectToCustomersFilter(it.typedId)
                        def customers = api.find("C", 0, 0, null, filter)
                        ...
         }
         
        Parameters:
        relatedObjectTypedId - TypedId of the related object. Its type needs to be one of:
        • 'PR': PriceRecord
        • 'CT': Contract
        • 'CTLI': ContractLineItem
        • 'RBA': RebateAgreement
        • 'RBALI': RebateAgreementLineItem
        Returns:
        A filter object
      • productToRelatedObjectsFilter

        Filter productToRelatedObjectsFilter​(String relatedObjectTypeCode,
                                             String sku)
        Creates a filter to be applied to a search on a related object type, limiting the result to objects of the related type that have a link to the given product.

        Example:

         def ras = api.find("RBA", 0, 1, null, null)
         ras.each {
                        def raId = it.typedId.tokenize(".")[0] as Long
                def raFilter = api.relatedObjectToCustomersFilter("RBA", raId)
                        def customers = api.find("C", 0, 0, null, filter)
                        ...
         }
         
        Parameters:
        relatedObjectTypeCode - TypeCode of the related object type. The possible values are:
        • 'PR': PriceRecord
        • 'CT': Contract
        • 'CTLI': ConttractLineItem
        • 'RBA': RebateAgreement
        • 'RBALI': RebateAgreementLineItem
        sku - Product.id to filter on
        Returns:
        A filter object
      • relatedObjectToProductsFilter

        Filter relatedObjectToProductsFilter​(String relatedObjectTypedId)
        Creates a filter to be applied to a product search, limiting the result to products that are linked to the given related object, the latter defined by its typedId.
        Parameters:
        relatedObjectTypedId - TypedId of the related object. Its type needs to be one of:
        • 'PR': PriceRecord
        • 'CT': Contract
        • 'CTLI': ContractLineItem
        • 'RBA': RebateAgreement
        • 'RBALI': RebateAgreementLineItem
        Returns:
        A filter object
      • isUserInGroup

        boolean isUserInGroup​(String userGroupName,
                              String loginUserName)
        Checks if the current user is a member of the given user group.

        Example:

         def user = api.user("loginName")
         if (api.isUserInGroup("Manager", user)) {
             ...
         }
         
        Parameters:
        userGroupName - The group name
        loginUserName - The login name of the user
        Returns:
        true or false
      • trace

        void trace​(String functionName,
                   String parameters,
                   Object result)
        Generates a trace message that can be used during testing of the logic. The Trace window has 3 columns (FunctionName, Parameters, Result), which you can use for your debugging messages. During the regular logic execution the trace messages are ignored. The parameters specify the output of the trace.

        Note: Consider commenting out the Trace messages before deploying to production

        Performance consideration: be carefull when using the api.trace() in a loop. If your logic (during testing) produces gigantic list of trace messages on the backend, then this big list must be transferred over internet to your local machine (when using Studio) and it can take significant time.

        Example:

             def listPrice = ...
             api.trace("listPrice", out.Currency, listPrice)
         
        Parameters:
        functionName - A function name. Regardless of the name, it can be any text you need to show up during testing. Usually, if you use trace() for output of a variable, this is used for the variable name. Note: Originally this was used as a name of the function which outputted the value, so that's why the name.
        parameters - Parameters to trace. Regardless of the name, it can be any text you need to show up during testing. Note: originally this was used to display values of parameters supplied into a function, hence the name.
        result - The result of the trace. Usually the value, which you're tracing during testing. You can supply any value you'd like to watch in the Trace window. Note: Originally this was used to show result of a function call, hence the name.
        See Also:
        trace(Object), trace(String, Object)
      • trace

        void trace​(String functionName,
                   Object result)
        See trace(String, String, Object) for description.

        Example:

             def salesOrg = ...
             api.trace("salesOrg", salesOrg)
         
        Parameters:
        functionName - A function name. Regardless of the name, it can be any text you need to show up during testing. Usually, if you use trace() for output of a variable, this is used for the variable name. Note: Originally this was used as a name of the function which outputted the value, so that's why the name.
        result - The result of the trace. Usually the value, which you're tracing during testing. You can supply any value you'd like to watch in the Trace window. Note: Originally this was used to show result of a function call, hence the name.
        See Also:
        trace(String, String, Object), trace(Object)
      • trace

        void trace​(Object result)
        See trace(String, String, Object) for description.

        Example:

             def price = ...
             api.trace(price)
         
        Parameters:
        result - The result of the trace. Usually the value, which you're tracing during testing. You can supply any value you'd like to watch in the Trace window. Note: Originally this was used to show result of a function call, hence the name.
        See Also:
        trace(String, String, Object), trace(String, Object)
      • log

        void log​(String msg,
                 Object arg1)
        This function is meant to be used by the Pricefx internally only. You should use logInfo(String, Object) or logWarn(String, Object). Logs a DEBUG message to the system error log which can be displayed in menu Tools / Logs / View Log. Log message can contain placeholders like {} which are then filled in dynamically with the argument's value. Note: To enable this function, you need to tick the setting "Allow Groovy logging to system log" in menu Tools / Configuration / General Settings.
        Parameters:
        msg - The log message to print
        arg1 - The arguments for the log message.
        See Also:
        logInfo(String, Object), logWarn(String, Object)
      • log

        void log​(Object msg)
        This function can be used by the support team only. You should use logInfo(Object) or logWarn(Object). Logs a DEBUG message to the system error log which can be displayed in menu Tools / Logs / View Log. Log message can contain placeholders like {} which are then filled in dynamically with the argument's value. Note: To enable this, you need to tick the setting "Allow Groovy logging to system log" in menu Tools / Configuration / General Settings.
        Parameters:
        msg - The message accompanying the exception
        See Also:
        logInfo(Object), logWarn(Object)
      • logInfo

        void logInfo​(String msg,
                     Object arg1)
        Logs an INFO warning message to the system error log which can be displayed in menu Tools / Logs / View Log. Log message can contain placeholders like {} which are then filled in dynamically with the argument's value. Note: To enable this, you need to tick the setting "Allow Groovy logging to system log" in menu Tools / Configuration / General Settings.

        Example:

         def sku = api.product("sku")
         api.markItemDirty()
         api.logInfo("SKU marked as dirty", sku)
         
        Parameters:
        msg - The log message to print
        arg1 - The arguments for the log message
        See Also:
        log(String, Object), logWarn(String, Object)
      • logInfo

        void logInfo​(Object msg)
        Logs a INFO message to the system error log which can be displayed in menu Tools / Logs / View Log. Log message can contain placeholders like {} which are then filled in dynamically with the argument's value. Note: To enable this, you need to tick the setting "Allow Groovy logging to system log" in menu Tools / Configuration / General Settings.

        Example:

         api.logInfo("No items to be calculated")
         
        Parameters:
        msg - The log message to print
        See Also:
        log(Object), logWarn(Object)
      • logWarn

        void logWarn​(String msg,
                     Object arg1)
        Logs a WARN message to the system error log which can be displayed in menu Tools / Logs / View Log. Log message can contain placeholders like {} which are then filled in dynamically with the argument's value. Note: To enable this, you need to tick the setting "Allow Groovy logging to system log" in menu Tools / Configuration / General Settings.

        Example:

         def sku = api.product("sku")
        
         if (checkItem()) {
              api.logWarn("Incorrect or missing 'sku' parameter", sku)
         }
         
        Parameters:
        msg - The log message to print
        arg1 - The arguments for the log message
        See Also:
        log(String, Object), logInfo(String, Object)
      • logWarn

        void logWarn​(Object msg)
        Logs a WARN message to the system error log which can be displayed in menu Tools / Logs / View Log. Log message can contain placeholders like {} which are then filled in dynamically with the argument's value. Note: To enable this, you need to tick "Allow Groovy logging to system log" in menu Tools / Configuration / General Settings.

        Example:

         api.logWarn("SKU cannot be null")
         
        Parameters:
        msg - The message accompanying the exception
        See Also:
        log(Object), logInfo(Object)
      • getParameter

        ContextParameter getParameter​(String parameterName)
        Retrieves an already generated (in the previous logic code) input parameter in the form of a ContextParameter object. This object can be used to set the label and the default value of the input, if it's required, etc.

        Example:

        
         def p = api.getParameter("Quantity")        // retrieve the context parameter with the same name as the input
         if (p != null && p.getValue() == null) {
           p.setLabel("Required Quantity")           // set the displayed label
           p.setRequired(true)                       // set the mandatory hint
           p.setReadOnly(false)                      // set the read only flag
           p.setValue(1)                             // set the default value with which the input is pre-populated
         }
         return qty ?: 1                             // if user doesn't specify a value, return 1
         
        Parameters:
        parameterName - The name of the input parameter to retrieve
        Returns:
        The parameter object or null
      • currentContext

        Map<String,​Object> currentContext​(String sku)
        In case of list processing (such as a price list or price grid), this method allows an easy access to values from the same list. It searches for the result record in the same list with the provided SKU.

        Note: If used within a context that has a secondary key, only the first object is returned.

        Parameters:
        sku - The SKU to look for
        Returns:
        The result record (entire record)
      • currentContext

        Map<String,​Object> currentContext​(String sku,
                                                String key2)
        In case of list processing (such as a price list or price grid), this method allows an easy access to values from the same list. It searches for the result record in the same list with the provided SKU.
        Parameters:
        sku - The SKU to look for
        key2 - The key2 to look for
        Returns:
        The result record (entire record)
      • previousContext

        Map<String,​Object> previousContext​(String sku)
        In case of (chained) price lists, this method allows for an easy retrieval of records from the previous list.

        Note: If used within a context that has a secondary key, only the first object is returned.

        Parameters:
        sku - The SKU to look for
        Returns:
        The result record (entire record)
      • previousContext

        Map<String,​Object> previousContext​(String sku,
                                                 String key2)
        In case of (chained) price lists, this method allows for an easy retrieval of records from the previous list.
        Parameters:
        sku - The SKU to look for
        key2 - The key2 to look for
        Returns:
        The result record (entire record)
      • contextName

        String contextName()
        The name of the current context, e.g. price list name, quote name etc.
        Returns:
        The name of a context
      • contextType

        String contextType()
        The type (type code string) of the current context.
        Returns:
        The type code string
      • contextTypedId

        String contextTypedId()
        The typedId of the current context.
        Returns:
        The typedId string
      • getProperty

        Object getProperty​(Object object,
                           String path)
        Serves as an optimized way to get to certain object attributes. The sandbox automatically converts "real" server objects into a map representation when the object is accessed. This is for safety (sandboxing) reasons. This process converts all object attributes. If only one specific attribute is of interest, this method shortcuts that as the underlying object is not exposed (and thus does not force the sandbox into conversion).
        Parameters:
        object - The object whose value to retrieve
        path - The attribute name
        Returns:
        The value of the attribute
      • getPropertyByElementName

        Object getPropertyByElementName​(Object object,
                                        String elementName)
        Gets object attributes by elementName. It works only for objects that have meta attributes which contain the element name. These are e.g. PLI, SIMI, PGI, MPLI.
        Parameters:
        object - The object whose value to retrieve
        elementName - The elementName value
        Returns:
        The value of the attribute or null if invalid object or no matching meta found
      • currentItem

        Object currentItem()
        In case of a list processing operation, this method gets the currently worked on record, for example:
        • for price calculations, it returns price list item or price grid item or quote item
        • for Calculated Field Set, it returns the row being processed, like Product/Customer/ProductExtension/PriceParameter row

        Important: The Pricelist line item is initially (during 1st pass) created only after the first logic execution (i.e. the PLI is created from the logic results). Which means, that during the first logic execution, the PLI does not exist yet and the method will return null.

        Example - in the Pricelist logic

         def currentItem = api.currentItem()
         def currentSku = currentItem != null ? currentItem.attribute20 : api.product("attribute20")
         

        Example - in the Calculated Field Set:

         def cost = api.currentItem()?.attribute1
         def exchangeRate = 1.1 // fixed rate for sample purposes
         return cost != null ? (cost * exchangeRate) : null
         
        Returns:
        The item object as a Map
        See Also:
        currentItem(String), currentItemByElementName(String)
      • currentItemByElementName

        Object currentItemByElementName​(String elementName)
        In case of a list processing operation, this method gets the currently worked on record's property by elementName.

        For example, when you want to get value of LPG column, which was generated by element named ListPrice, you do not need to know, that it was stored in column attribute3, but you can ask for the value using the name of the element, which provided the value.

        Parameters:
        elementName - The element name
        Returns:
        The item's property value
        See Also:
        currentItem(String)
      • currentItem

        Object currentItem​(String attributeName)
        Same as currentItem() but returns only value of the given attribute.

        Example:

         def activePrice = api.currentItem("activePrice")
         
        Parameters:
        attributeName - The attribute to retrieve
        Returns:
        The value of the attribute
        See Also:
        currentItemByElementName(String)
      • contextSkuSet

        Set<Object> contextSkuSet​(int startRow)
        Returns a set of SKUs which comprise so-called 'SKU context' of the current formula execution.

        The form of the SKU context differs, e.g., in case of the product detail formula executed via price grid details, the resulting set will contain all SKUs of the left-pane grid.

        Note #1: If the SKU context is not supported by the current formula execution, null is returned.

        Note #2: A maximum of 200 SKUs is returned per one call. If there are more, startRow must be used to get all SKUs in the set.

        Parameters:
        startRow - The starting row of the result set
        Returns:
        A set of SKUs or null if the SKU context is not available for the current formula execution
      • find

        List<Object> find​(String typeCode,
                          Filter... filters)
        Deprecated.
        use find(String, int, int, String, List, Filter...) in order to always specify the fields to be returned because of performance.
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. A maximum of 200 items is returned. You should use find(String, int, int, String, List, Filter...) instead because of performance reasons.
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        List of objects represented as Maps
        See Also:
        stream(String, String, Filter...), count(String, Filter...)
      • find

        List<Object> find​(String typeCode,
                          int startRow,
                          Filter... filters)
        Deprecated.
        use find(String, int, int, String, List, Filter...) because of performance you should always specify the fields to be returned.
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. A maximum of 200 items is returned. The start row parameter can be used to page through more than 200 results. If you don't need all the columns to be fetched, you should use find(String, int, int, String, List, Filter...) instead because of performance reasons.
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        filters - An optional list of filters (that will evaluated using AND operator)
        startRow - The starting row of the result set
        Returns:
        List of objects represented as Maps
        See Also:
        stream(String, String, Filter...), count(String, Filter...)
      • find

        List<Object> find​(String typeCode,
                          int startRow,
                          String sortBy,
                          Filter... filters)
        Deprecated.
        use find(String, int, int, String, List, Filter...) because of performance you should always specify the fields to be returned.
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. A maximum of 200 items is returned. The start row parameter can be used to page through more than 200 results. If you don't need all the columns to be fetched, you should use find(String, int, int, String, List, Filter...) instead because of performance reasons.

        Example:

         def sku = api.product("sku")
        
         def filters = [
             Filter.equal("name", "Competition"),
             Filter.equal("sku", sku),
         ]
        
         // sort by competitor's price ASC
         def competitors = api.find("PX", 0, "attribute1", *filters)
        
         competitors.each {
             ...
         }
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        startRow - The starting row of the result set
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        List of objects represented as Maps
        See Also:
        stream(String, String, Filter...), count(String, Filter...)
      • find

        List<Object> find​(String typeCode,
                          int startRow,
                          int maxRows,
                          String sortBy,
                          Filter... filters)
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. The maximum number of rows retrieved is determined by the formulaEngine.script.findMaxResults system parameter. The maxRows parameter can only set to lower values.

        Example:

         def sku = api.product("sku")
        
         def filters = [
             Filter.equal("name", "Competition"),
             Filter.equal("sku", sku),
         ]
        
         // sort by competitor's price ASC
         def competitors = api.find("PX", 0, api.getMaxFindResultsLimit(), "-attribute2", *filters)
        
         competitors.each {
             ...
         }
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        startRow - The starting row of the result set
        maxRows - The maximum number of rows to retrieve. Value can be up to getMaxFindResultsLimit(). If set to 0 it will default to 200
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        List of objects represented as Maps
        See Also:
        getMaxFindResultsLimit(), stream(String, String, Filter...), count(String, Filter...)
      • find

        List<Object> find​(String typeCode,
                          int startRow,
                          int maxRows,
                          String sortBy,
                          List<String> fields,
                          Filter... filters)
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. The maximum number of rows retrieved is determined by the formulaEngine.script.findMaxResults system parameter. The maxRows parameter can only set to lower values than that.

        Example:

         def sku = api.product("sku")
        
         def filters = [
             Filter.equal("name", "Competition"),
             Filter.equal("sku", sku),
         ]
        
         // sort by competitor's price ASC
         def competitors = api.find("PX", 0, api.getMaxFindResultsLimit(), "-attribute2", ["attribute2", "attribute5", "attribute6"], *filters)
        
         competitors.each {
             ...
         }
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        startRow - The starting row of the result set
        maxRows - The maximum number of rows to retrieve. Value can be up to getMaxFindResultsLimit(). If set to 0 it will default to 200
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        fields - A list of fields to returned in the result. If you really need all fields, you can set this parametr to null
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        List of objects represented as Maps
        See Also:
        getMaxFindResultsLimit(), stream(String, String, List, Filter...), count(String, Filter...)
      • find

        List<Object> find​(String typeCode,
                          int startRow,
                          int maxRows,
                          String sortBy,
                          List<String> fields,
                          boolean distinctValuesOnly,
                          Filter... filters)
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. The maximum number of rows retrieved is determined by the formulaEngine.script.findMaxResults system parameter. The maxRows parameter can only set lower values than that.
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        startRow - The starting row of the result set
        maxRows - The maximum number of rows to retrieve. Value can be up to getMaxFindResultsLimit(). If set to 0 it will default to 200
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        fields - A list of fields to returned in the result. If you really need all fields, you can set this parametr to null
        distinctValuesOnly - Fetches distinct/all values. The use case here is fetching distinct single column values.
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        List of objects represented as Maps
        See Also:
        getMaxFindResultsLimit(), stream(String, String, List, boolean, Filter...), count(String, Filter...)
      • find

        List<Object> find​(String typeCode,
                          int startRow,
                          int maxRows,
                          String sortBy,
                          Map<String,​String> fields,
                          boolean distinctValuesOnly,
                          Filter... filters)
        The Swiss army knife method of the API. With this method you can search for all types of objects with a freestyle query. The filters are ANDed together. The maximum number of rows retrieved is determined by the formulaEngine.script.findMaxResults system parameter. The maxRows parameter can only set lower values than that.
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        startRow - The starting row of the result set
        maxRows - The maximum number of rows to retrieve. Value can be up to getMaxFindResultsLimit(). If set to 0 it will default to 200
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        fields - A map of pairs [fieldname : aggregation] holding fields to be returned in the result where aggregation can be one of SUM, AVG, MIN or MAX The key of the map is the field name. The value can be a field operator like SUM, AVG, MIN or MAX.
        distinctValuesOnly - Fetches distinct/all values. The use case here is fetching distinct single column values.
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        List of objects represented as Maps
        See Also:
        getMaxFindResultsLimit(), stream(String, String, Map, boolean, Filter...), count(String, Filter...)
      • stream

        AbstractProducer.ResultIterator stream​(String typeCode,
                                               String sortBy,
                                               Filter... filters)
        Searches for all types of objects with a freestyle query and iterates over the result set. The filters are ANDed together. If you don't need all the columns to be fetched, you should use stream(String, String, List, Filter...) instead because of performance reasons.

        Important note: you have to close the iterator after iterating the data using Closeable.close().

        Example:

        
         def filters = [
              Filter.equal("attribute2", "Active")
         ]
        
         def products = api.stream("P", "-attribute1", *filters)
        
         products.each { product ->
              ...
         }
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        The result implements the Iterator interface, allowing for iteration over all records in the scope of the query.
        See Also:
        find(String, int, String, Filter...), count(String, Filter...)
      • stream

        AbstractProducer.ResultIterator stream​(String typeCode,
                                               String sortBy,
                                               List<String> fields,
                                               Filter... filters)
        Searches for all types of objects with a freestyle query and iterates over the result set. The filters are ANDed together.

        This method is not supported in the Syntax Check mode.

        Important note: you have to close the iterator after iterating the data using Closeable.close().

        Example:

        
         def filters = [
              Filter.equal("attribute2", "Active")
         ]
        
         def products = api.stream("P", "-attribute1", ["attribute2"], *filters)
        
         products.each { product ->
              ...
         }
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        fields - A list of attributes you want to return in the result, i.e. skip all attributes not contained in the list that the search would return otherwise.
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        The result implements the Iterator interface, allowing for iteration over all records in the scope of the query.
        See Also:
        find(String, int, int, String, List, Filter...), count(String, Filter...)
      • stream

        AbstractProducer.ResultIterator stream​(String typeCode,
                                               String sortBy,
                                               List<String> fields,
                                               boolean distinctValuesOnly,
                                               Filter... filters)
        Searches for all types of objects with a freestyle query and iterates over the result set. The filters are ANDed together.

        This method is not supported in the Syntax Check mode.

        Important note: you have to close the iterator after iterating the data using Closeable.close().

        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        fields - A list of attributes you want to return in the result, i.e. skip all attributes not contained in the list that the search would return otherwise.
        distinctValuesOnly - Fetches distinct/all values. The use case here is fetching distinct single column values.
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        The result implements the Iterator interface, allowing for iteration over all records in scope of the query.
        See Also:
        find(String, int, int, String, List, boolean, Filter...), count(String, Filter...)
      • stream

        AbstractProducer.ResultIterator stream​(String typeCode,
                                               String sortBy,
                                               Map<String,​String> fields,
                                               boolean distinctValuesOnly,
                                               Filter... filters)
        Searches for all types of objects with a freestyle query and iterates over the result set. The filters are ANDed together.

        This method is not supported in the Syntax Check mode.

        Important note: you have to close the iterator after iterating the data using Closeable.close().

        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        sortBy - String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort order
        fields - Map of pairs [fieldname : aggregation] holding fields to be returned in the result where aggregation can be one of SUM, AVG, MIN or MAX The key of the map is the field name. The value can be a field operator like SUM, AVG, MIN or MAX
        distinctValuesOnly - Fetches distinct/all values. The use case here is fetching distinct single column values.
        filters - An optional list of filters (that will evaluated using AND operator)
        Returns:
        The result implements the Iterator interface, allowing for iteration over all records in scope of the query.
        See Also:
        find(String, int, int, String, Map, boolean, Filter...), count(String, Filter...)
      • namedEntities

        List<Map<String,​Object>> namedEntities​(List<Object> objects)
        When given a list of entities (result of api.find,...), it converts the list of meta attributed entities to a list of maps where each map is a serialized entity which keys are using field names from attribute meta object. i.e. converts attributeX fields to names defined in metadata
        Parameters:
        objects - list of entities (results of api.find,...)
        Returns:
        list of serialized entities where keys have the names from meta data
      • emit

        boolean emit​(Object obj)
              throws InterruptedException
        Emits an object to be consumed by an external thread. Requires a blocking emitQueue to be set in the FormulaEngineContext and a consuming thread to take the emitted objects from the queue. See also FeederFormulaExecutor.

        This method is not supported in the Syntax Check mode.

        Parameters:
        obj - The object to be emitted/inserted in the emit queue
        Returns:
        True if the object is successfully inserted in the queue, false otherwise.
        Throws:
        InterruptedException - if interrupted while waiting
      • emitDMScopedObject

        boolean emitDMScopedObject​(String typedId,
                                   DMDataSlice slice)
                            throws InterruptedException
        Emits the partitioned object - to be consumed by a PA allocation task (a PA calculation task with a feeder formula calling this method, and a regular formula accepting each emitted partitioned object as its currentItem context, and distributing one or more partitioned object accruals over the set of PA rows which have contributed to those accruals in some way (by revenue, bvolume...).
        Parameters:
        typedId - The typedId of the PartitionedObject to emit
        slice - DMDataSlice defines DM slice to which given partitioned object contributes. Make sure it contains valid dateFieldName via DMDataSlice.setDateFieldName(String)
        Returns:
        True if the object is successfully inserted in the queue, false otherwise.
        Throws:
        InterruptedException
      • emitRebateRecords

        void emitRebateRecords​(String dateFieldName,
                               String sortBy,
                               Filter... filters)
                        throws InterruptedException
        Emits the rebate records matching the given search criteria - to be consumed by a PA allocation task (a PA calculation task with a feeder formula calling this method, and a regular formula accepting each emitted RebateRecord as its currentItem context, and distributing one or more RebateRecord accruals over the set of PA rows which have contributed to those accruals in some way (by revenue, bvolume...).
        Parameters:
        dateFieldName - The name of the field to be substituted in the RebateRecord calculationBase (a DMDataSlice object that includes a generic time dimension filter)
        sortBy - The RebateRecord field on which to sort
        filters - The filters to apply to the RebateRecord search
        Throws:
        InterruptedException - if interrupted while waiting
      • count

        int count​(String typeCode,
                  Filter... filters)
        Returns the number of records that a corresponding find(String, int, int, String, List, Filter...) would return.
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        filters - A list of Filter objects that are ANDed together
        Returns:
        The number of matching records
      • findLookupTable

        LookupTable findLookupTable​(String tableName)
        Finds a price parameter table object (LT)
        • of the given name
        • which is valid at current target date
        • which Status is Active or Simulation Only (Simulation Only tables will be used only when the logic is run as simulation)
        • if executed during simulation, it must have matching Simulation Set

        Performance consideration: There is no caching of the values, so the caching should be considered.

        Example:

         def table = api.findLookupTable("PricelistApprovalLevels")
        
         def row = api.find("MLTV", 0, 1, null,
        
                              Filter.equal("lookupTable.id", table?.id),
        
                              Filter.equal("name", api.product("BusinessUnit"))
                   )?.getAt(0)
         

        Parameters:
        tableName - The name of the price parameter table
        Returns:
        The price parameter table object (as Map) or null if the table does not exists or it's validAfter > targetDate
      • findLookupTableValues

        List<Object> findLookupTableValues​(String tableName,
                                           Filter... filters)
        Returns fitered list of rows of a price parameter table. It will use the Price Parameter table
        • of the given name
        • which is valid at current target date
        • which Status is Active or Simulation Only (Simulation Only tables will be used only when the logic is run as simulation)
        • if executed during simulation, it must have matching Simulation Set

        Performance Considerations: There is no caching of the values, so you should consider caching it yourself.

        Example:

         def salesOrgMap = api.findLookupTableValues("SalesOrg").collectEntries{
                                [(it.name) : it.name]
                           }
        
         return api.option("SalesOrg", salesOrgMap.keySet() as List, salesOrgMap)
         

        Example:

         api.retainGlobal = true
        
         // for the first time
         if (api.global.salesOrgs == null) {
             // store all values as a Map [name : value] to global cache
             api.global.salesOrgs = api.findLookupTableValues("SalesOrg").collectEntries {
                                                   [(it.name): it.value]
                                    }
         }
        
         return api.global.salesOrgs
         
        Parameters:
        tableName - The name of the price parameter table
        filters - Optional extra Filter
        Returns:
        The price parameter table values or null
        See Also:
        findLookupTableValues(String, String, Filter...)
      • findLookupTableValues

        List<Object> findLookupTableValues​(String tableName,
                                           String sortBy,
                                           Filter... filters)
        Returns sorted rows of a Price Parameter table (optionally filtered). It will use the Price Parameter table
        • of the given name
        • which is valid at current target date
        • which Status is Active or Simulation Only (Simulation Only tables will be used only when the logic is run as simulation)
        • if executed during simulation, it must have matching Simulation Set
        There is no caching of the values, so you should should consider caching it yourself.

        Example:

         api.retainGlobal = true
        
         // for the first time
         if (api.global.salesOrgs == null) {
             // store all values as a Map [name : value] to global cache
             api.global.salesOrgs = api.findLookupTableValues("SalesOrg", "-name").collectEntries {
                 [(it.name): it.value]
             }
         }
        
         return api.global.salesOrgs
         
        Parameters:
        tableName - The name of the price parameter table
        sortBy - Name of column to be used for sorting of the rows. If char "-" precedes the name, it will do reverse order (for example "-key1"). Use null if no sorting is required.
        filters - Optional extra Filter
        Returns:
        The price parameter table values or null
        See Also:
        findLookupTableValues(String, Filter...)
      • findWorkflowInfo

        WorkflowInfo findWorkflowInfo​(String approvableTypeCode,
                                      Object approvableId)
        Finds active workflows for the given approvable. You can get the same information as displayed in the workflow UI.

        Example:

         def quoteUniqueName = "P-123"
         def quote = api.find('Q', 0, 1, Filter.equal("uniqueName", quoteUniqueName)).getAt(0)
         return quote ? api.findWorkflowInfo('Q', quote.id) : null
         
        Parameters:
        approvableTypeCode - The type code of approvable. Approvables are e.g. quotes, rebate agreements, data change requests etc.
        approvableId - ID of the approvable
        Returns:
        Table like structure resembling workflow UI or null if not found
        See Also:
        findPreviousWorkflowInfo(String, String...), findPreviousApprovableState(String, String...)
      • findPreviousApprovableState

        Map<String,​Object> findPreviousApprovableState​(String typedId,
                                                             String... workflowStatuses)
        Finds the previous approvable entity state if some DENIED or WITHDRAWN workflow for the approvable exists.
        Parameters:
        typedId - Approvable entity typed ID
        workflowStatuses - Only DENIED or WITHDRAWN are supported
        Returns:
        State of the approvable entity when its previous workflow was DENIED or WITHDRAWN
        See Also:
        findWorkflowInfo(String, Object)
      • findPreviousWorkflowInfo

        WorkflowInfo findPreviousWorkflowInfo​(String typedId,
                                              String... workflowStatuses)
        Finds the approvable entity previous workflow history if some DENIED or WITHDRAWN workflow for the approvable exists.
        Parameters:
        typedId - Approvable entity typed ID
        workflowStatuses - Only DENIED or WITHDRAWN are supported
        Returns:
        Workflow history, see net.pricefx.workflowengine.WorkflowInfo
        See Also:
        findWorkflowInfo(String, Object)
      • findCustomerAssignments

        List<CustomerAssignment> findCustomerAssignments​(String customerId)
        Finds all assignment records for the given customerId. Also matches by CustomerGroup definitions.
        Parameters:
        customerId - The customer whose assignments are searched for
        Returns:
        A list of assignment records
      • findPricelists

        List<Pricelist> findPricelists​(Date targetDate,
                                       String listName)
        Returns a list of price lists that match the targetDate (i.e. list's targetDate <= targetDate and expiryDate > targetDate).
        Parameters:
        targetDate - The targetDate to use
        listName - Price list name. If null, the list name is not included in search.
        Returns:
        The list of matching price lists
      • findSimulations

        List<Simulation> findSimulations​(Date targetDate,
                                         String simulationName)
        Returns a list of simulations that match the targetDate (i.e. list's targetDate <= targetDate).
        Parameters:
        targetDate - The targetDate to use
        simulationName - Simulation name. If null, the simulation name is not included in search.
        Returns:
        The list of matching simulations
      • findPriceGrids

        List<PriceGrid> findPriceGrids​(Date targetDate,
                                       String priceGridName)
        Returns a list of price grids that match the targetDate (i.e. price grid's targetDate <= targetDate).
        Parameters:
        targetDate - The targetDate to use
        priceGridName - Price grid name. If null, the price grid name is not included in search.
        Returns:
        The list of matching price grids
      • findCalculatedFieldSets

        List<CalculatedFieldSet> findCalculatedFieldSets​(Date targetDate,
                                                         String cfsName)
        Returns a list of calculated field sets that match the targetDate.
        Parameters:
        targetDate - Target date for the CFS
        cfsName - CFS name. If null, the CFS name is not included in search.
        Returns:
        The list of matching calculated field sets
      • findManualPricelists

        List<ManualPricelist> findManualPricelists​(Date targetDate,
                                                   String listName)
        Returns a list of manual price lists that match the targetDate (i.e. list's validAfter <= targetDate and expiryDate > targetDate).
        Parameters:
        targetDate - The targetDate to use
        listName - Price list name. If null, the list name is not included in search.
        Returns:
        The list of matching price lists
      • findApprovedPricelistItems

        List<SummaryCalculableObjectItem> findApprovedPricelistItems​(String sku)
        Returns a list of summary items. One item is returned for every matching (=same SKU) PLI or XPLI which is in an approved list.
        Parameters:
        sku - The SKU to filter on
        Returns:
        A list of summary items
      • findCustomersInGroup

        List<Customer> findCustomersInGroup​(CustomerGroup group)
        Retrieves a list of customers that match the given CustomerGroup (returns first 200 entries).
        Parameters:
        group - The group to match
        Returns:
        A list of customers
      • findCustomersInGroup

        List<Customer> findCustomersInGroup​(CustomerGroup group,
                                            int startRow,
                                            String sortBy)
        Retrieves a list of customers that match the given CustomerGroup with custom paging and sorting.
        Parameters:
        group - The customer group
        startRow - The starting row number (maximum 200 rows returned at once)
        sortBy - A sort key. null if no sorting is required.
        Returns:
        A list of customers
      • getManualOverride

        Object getManualOverride​(String elementName)
        Returns a user entered value that overrides the calculated result of a logic element.

        Note that the manualOverride works as a flag - when it is set for an element, the final value of that element is taken from the manually entered value and the calculation of that element does not run at all. If this flag is not set, the final value is the calculated result.

        Parameters:
        elementName - The formula/result element that is overridden
        Returns:
        The overridden value or null if not overridden
      • removeManualOverride

        void removeManualOverride​(String elementName)
        Removes a user entered value that overrides the calculated result of a logic element.

        If you have a condition to remove the manual override, it is recommended to put this condition in a separate logic element which is always executed (not in the same one which has the manual override allowed; the reason is that once the user enters a value manually, the element calculation does not run at all, so the condition would not be evaluated). Note also that a logic element with api.removeManualOverride() must be before an element which is cleared.

        Parameters:
        elementName - The formula/result element that is overridden
      • abortCalculation

        void abortCalculation()
        Aborts the current item (e.g. pricelist line, quote line) calculation - i.e. stops the execution of subsequent elements of the logic. The subsequent logic elements are not executed and the calculation engine continues with calculation of the next item.

        Important: This function only sets the abortCalculation flag, so the element where api.abortCalculation() is called finishes its execution and still returns a value (but it is the last element returning a value).

        Note: This function is often called together with isSyntaxCheck() after the parameters are gathered.

        Example of element logic:

         if (api.isSyntaxCheck()) {
           api.abortCalculation()
         }
         

        Example of element logic:

         def price = ...
        
         if (!price) {
           api.abortCalculation()
         }
        
         return price  //!!! This line will still be executed during the Syntax Check, the logic will be aborted only after this element finishes
         
      • abortCalculation

        void abortCalculation​(boolean keepOld)
        Aborts the current item calculation. The subsequent logic elements are not executed and the calculation engine continues with calculation of the next item. This function only sets the abortCalculation flag, so the element where abortCalculation is called still returns a value (and is the last element returning a value). This function can be called together with isSyntaxCheck() after the parameters are gathered.

        Parameters:
        keepOld - Should the old outputs be retained? Only applicable for quote and contract calculation!
      • abortSyntaxCheck

        void abortSyntaxCheck()
        Aborts the current item parameter determination. This helps in logic with many elements to tell the engine to not to spend more time on next elements when logic author is sure that there is no any statement that would generate any new inputs. This function can be called together with isSyntaxCheck() after the parameters are gathered.
      • throwException

        void throwException​(String errorMessage)
                     throws XExpression
        Throws a calculation exception with the specified message and aborts the calculation logic execution immediately.

        Sample use cases:

        • in Workflow logic - when the Workflow logic cannot find important/vital data needed for building of the approval steps, then it can throw exception, which immediately stops the submission process and the Quote will be still in Draft.
        • in Quote logic - to stop processing Quote Line calculation, when the important inputs (or values) are not available. If the calculation was called as part of the Submission process, the process stops, and the Quote stays in Draft state.
        Parameters:
        errorMessage - The error message that is displayed
        Throws:
        XExpression - The custom calculation exception
      • markItemDirty

        void markItemDirty​(String sku)
        Sets the dirty flag on the specified item, i.e. the second calculation run will be triggered and this item will be included in the 2nd pass. If used in a MatrixPricelist/MatrixSimulation (i.e. on objects that have a secondary key), all items with that SKU are marked as dirty. See also getIterationNumber(), markItemClean(). The maximum number of dirty passes is defined by the server configuration constant maxDirtyCalculations defined for the whole instance. The default is 1 dirty pass.
        Parameters:
        sku - The item to have the dirty flag set
        See Also:
        markItemClean(String)
      • markItemDirty

        void markItemDirty​(String sku,
                           String key2)
        Sets the dirty flag on the specified item, i.e. the second calculation run will be triggered and this item will be included in the 2nd pass. The maximum number of dirty passes is defined by the server configuration constant maxDirtyCalculations defined for the whole instance. The default is 1 dirty pass. See also getIterationNumber(), markItemClean().
        Parameters:
        sku - The item to have the dirty flag set
        key2 - key2 field
        See Also:
        markItemClean(String, String)
      • markItemDirty

        void markItemDirty()
        Sets the dirty flag on the specified item, i.e. the second calculation run will be triggered and this item will be included in the 2nd pass. The maximum number of dirty passes is defined by the server configuration constant maxDirtyCalculations defined for the whole instance. The default is 1 dirty pass. See also getIterationNumber(), markItemClean().
        See Also:
        markItemClean()
      • isSecondPass

        boolean isSecondPass()
        Deprecated.
        Use getIterationNumber() > 0 instead.
        Determines if the calculation is a dirty pass. Does not necessarily mean it is a 2nd pass calculation.
        Returns:
        true if is in a dirty pass
      • getIterationNumber

        int getIterationNumber()
        Returns the number of iterations this list has been calculated during this cycle. 0 means: initial calculation (non-dirty) 1 means: 1st dirty pass, markItemDirty() was called in the previous pass 2 means: 2nd dirty pass, markItemDirty() was called in the previous pass and so on The maximum number of dirty passes is defined by the server configuration constant maxDirtyCalculations defined for the whole instance. The default is 1 dirty pass.
        Returns:
        The iteration number
      • jsonDecode

        Object jsonDecode​(String json)
        A utility method to decode a JSON string into a Map representation.
        Parameters:
        json - The input JSON string
        Returns:
        The parsed JSON as a Map
      • jsonDecodeList

        Object jsonDecodeList​(String json)
        A utility method to decode a JSON string into a List representation.
        Parameters:
        json - The input JSON string
        Returns:
        The parsed JSON as a List
      • jsonEncode

        Object jsonEncode​(Object input)
        A utility method to encode an object to a JSON string. Omits all null values in the output.
        Parameters:
        input - The input object, usually a map
        Returns:
        Encoded object
      • jsonEncode

        Object jsonEncode​(Object input,
                          boolean omitNull)
        A utility method to encode an object to a JSON string.
        Parameters:
        input - The input object, usually a map
        omitNull - Determines is null values should be omitted
        Returns:
        Encoded object
      • criticalAlert

        void criticalAlert​(String msg)
        Marks the current logic element as a critical alert and provides the given message.

        In a price grid, price list or in a quote line item, it marks the whole record with a dark red background color.

        In the calculation results (e.g. in Quote line results), it displays a red circle with an exclamation mark next to the element.

        To display the error message for price grids and price lists, click the arrow in the Detail column.

        Displayed only if called from an element that has its 'Display mode' enabled for the given context ('PriceGrids', 'Pricelists' or 'Quote Configurator').

        Note: when used in a quote line context, it blocks submission of the quote.

        Parameters:
        msg - The alert message
        See Also:
        redAlert(String), yellowAlert(String)
      • redAlert

        void redAlert​(String msg)
        Marks the current logic element with a red alert and provides the given message.

        In a price grid, price list or in a quote line item, it marks the corresponding field background with a red background color.

        In the calculation results (e.g. in Quote line results), it displays a plain red circle next to the element.

        To display the error message for price grids and price lists, click the arrow in the Detail column.

        Displayed only if called from an element that has its 'Display mode' enabled for the given context ('PriceGrids', 'Pricelists' or 'Quote Configurator').

        Parameters:
        msg - The alert message
        See Also:
        criticalAlert(String), yellowAlert(String)
      • yellowAlert

        void yellowAlert​(String msg)
        Marks the current logic element with a yellow alert and provides the given message.

        In a price grid, price list or in a quote line item, it marks the corresponding field background with a yellow background color.

        In the calculation results (e.g. in Quote line results), it displays a plain yellow circle next to the element.

        To display the error message for price grids and price lists, click the arrow in the Detail column.

        The Alert is displayed only if called from an element that has its 'Display mode' enabled for the given context ('PriceGrids', 'Pricelists' or 'Quote Configurator').

        Parameters:
        msg - The alert message
        See Also:
        criticalAlert(String), redAlert(String)
      • setAlertMessage

        void setAlertMessage​(String msg)
        Marks the current formula element with the given alert message. If one was already set by means of a yellowAlert, redAlert or criticalAlert call, then that message is replaced. When not raising an alert through any of these calls, but still setting a message with this method, then the message will be displayed wherever calculation results are shown with alert messages, but withoud any yellow or red background coloring.
        Parameters:
        msg - The alert message
      • buildFlexChart

        ResultFlexChart buildFlexChart​(String baseTemplateToUse,
                                       Object definition)
        Deprecated.
        Creates a FlexChart from the passed definition by merging it with options defined within the baseTemplateToUse template.

        Although it may change in future releases, for now, a FlexChart is nothing else than a Highcharts chart. Therefore, the passed definition (also applies to the baseTemplateToUse template) must denote Highcharts options - please consult Highcharts documentation for more details, and note that FlexCharts must comply to the outdated Highcharts release 4.

        Since Highcharts options are normally specified by a JavaScript object literal, the passed definition must be either a JSON string representing such object literal, or any object which can be mapped to such JSON representation. Therefore, typically the definiton will be passed as a map of maps.

        Example:

         def definition = [
           chart: [
             type: "bar"
           ],
           title: [
             text: "A common FlexChart"
           ],
           series: [
            [
              data: [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
            ]
           ]
         ]
        
         api.buildFlexChart(definition)
         
        Note that not all Highcharts options are supported. Moreover, usage of some options is prohibited deliberately. These are currently global, events and every JavaScript function-based options.

        Note: FlexChart templates are defined by an administrator in the 'Configuration' section.

        Parameters:
        baseTemplateToUse - The name of the template to use as a basis for merging with the passed definition; if null, the predefined Default template is used
        definition - The definition of the FlexChart; currently, this will typically be a string or map of maps containing Highcharts options
        Returns:
        A helper object linking the resulting FlexChart, baseTemplateToUse and type of the result - which will always be 'FLEXCHART', here
        See Also:
        http://api.highcharts.com/highcharts, http://www.highcharts.com/docs, http://json.org, buildFlexChart(Object), buildHighchart(Map)
      • buildHighmap

        ResultHighmap buildHighmap​(Map<String,​?> definition)
        Creates a ResultHighmap from the passed definition.
        As opposed to FlexChart, the definition is passed straight to the Highmaps library, currently release 8.0. There is no validation, no templates merging, and JavaScript functions are not supported. HighChart provide better performance than FlexChart since
        Parameters:
        definition - The definition of the Highmap as a map of maps and arrays
        Returns:
        buildHighmap object
        See Also:
        https://www.highcharts.com/docs, https://api.highcharts.com/highmaps
      • newAdaptiveHistogram

        AdaptiveHistogram newAdaptiveHistogram()
        Creates a histogram that adapts to an unknown data distribution. It keeps a more or less constant resolution throughout the data range by increasing the resolution where the data is more dense. For example, if the data has such a distribution that most of the values lie in the 0-5 range and only a few are in the 5-10 range, the histogram would adapt and assign more counting buckets to the 0-5 range and less to the 5-10 range. The histogram provides a method to obtain the accumulative density function for a given data point (getValueForPercentile), and a method to obtain the data point that splits the data set at a given percentile (getValueForPercentile).
        Returns:
        A new AdaptiveHistogram object
      • getPricelistSummaryQuery

        ItemSummaryQuery<Pricelist> getPricelistSummaryQuery()
        Creates a summary query object that can be parameterized and is then subsequently used in runSummaryQuery(ItemSummaryQuery). This query runs against price list(s).
        Returns:
        The query definition object
      • getSimulationSummaryQuery

        ItemSummaryQuery<Simulation> getSimulationSummaryQuery()
        Creates a summary query object that can be parameterized and is then subsequently used in runSummaryQuery(ItemSummaryQuery). This query runs against simulation(s).
        Returns:
        The query definition object
      • getPriceGridSummaryQuery

        ItemSummaryQuery<PriceGrid> getPriceGridSummaryQuery()
        Creates a summary query object that can be parameterized and is then subsequently used in runSummaryQuery(ItemSummaryQuery). This query runs against price grid(s).
        Returns:
        The query definition object
      • getRebateRecordSummaryQuery

        ItemSummaryQuery<RebateRecordSet> getRebateRecordSummaryQuery()
        Creates a summary query object that can be parameterized and is then subsequently used in runSummaryQuery(ItemSummaryQuery). This query runs against rebate records.
        Returns:
        The query definition object
      • runSummaryQuery

        List<Map<String,​Object>> runSummaryQuery​(ItemSummaryQuery<? extends CalculableObject> query)
        Runs (executes) a summary query defined by the parameterized query object which was created by one of the getXXXSummaryQuery calls.
        Parameters:
        query - The query to execute
        Returns:
        The result set of the query
      • createConfiguratorEntry

        ConfiguratorEntry createConfiguratorEntry​(InputType type,
                                                  String name)
        Creates a configurator entry object and adds the specified input parameter as the first parameter to the configurator entry. If the parameter had a value in the previous round trip, that value is set automatically.
        Parameters:
        type - Input type of the parameter. Valid enum values are: PRODUCT, PRODUCTGROUP, CUSTOMER, CUSTOMERGROUP, USERENTRY, STRINGUSERENTRY, OPTION, INTEGERUSERENTRY, BOOLEANUSERENTRY, DATEUSERENTRY, TIMEUSERENTRY, DATETIMEUSERENTRY, MULTITIERENTRY, INPUTMATRIX, OPTIONS, MATRIXLOOKUP, LOOKUP, FILTERBUILDER, DMFILTERBUILDER, DMFIELD, DMDIMFILTER, CONFIGURATOR, HIDDEN
        name - The name of the parameter
        Returns:
        The configurator entry with the input parameter added
      • createConfiguratorEntry

        ConfiguratorEntry createConfiguratorEntry​(InputType type,
                                                  String name,
                                                  Date targetDate)
        Creates a configurator entry object and adds the specified input parameter as the first parameter to the configurator entry. If the parameter had a value in the previous round trip, that value is set automatically.
        Parameters:
        type - Input type of the parameter. Valid enum values are: PRODUCT, PRODUCTGROUP, CUSTOMER, CUSTOMERGROUP, USERENTRY, STRINGUSERENTRY, OPTION, INTEGERUSERENTRY, BOOLEANUSERENTRY, DATEUSERENTRY, TIMEUSERENTRY, DATETIMEUSERENTRY, MULTITIERENTRY, INPUTMATRIX, OPTIONS, MATRIXLOOKUP, LOOKUP, FILTERBUILDER, DMFILTERBUILDER, DMFIELD, DMDIMFILTER, CONFIGURATOR, HIDDEN
        name - The name of the parameter
        targetDate - Target date for the input parameter (not applicable to all input types)
        Returns:
        The configurator entry with the input parameter added
      • createConfiguratorEntry

        ConfiguratorEntry createConfiguratorEntry()
        Creates an empty configurator entry object. Must be filled with input parameters by calling createParameter on the object.
        Returns:
        The configurator entry
      • createConfiguratorEntryArray

        ConfiguratorEntryArray createConfiguratorEntryArray​(Object... entries)
        Creates a configurator entry array object which is to be returned from a logic element. Allows dynamic setup of the configurator entries.
        Parameters:
        entries - 0..N configurator entries. Supports also list nesting.
        Returns:
        The configurator entry array object with defined methods for further anrichment of the array as ConfiguratorEntryArray#addEntry(ConfiguratorEntry), ConfiguratorEntryArray#setEntries(List) or ConfiguratorEntryArray#getEntries()
      • configurator

        Object configurator​(String configuratorName,
                            String formulaName)
        Parameters:
        configuratorName - The name of the configurator, similar to other options' names
        formulaName - The name of the configurator formula which is used to drive the input selections
        Returns:
        The result of the configurator
      • configurator

        Object configurator​(String configuratorName,
                            String formulaName,
                            Object resultName)
        Parameters:
        configuratorName - The name of the configurator, similar to other options' names
        formulaName - The name of the configurator formula which is used to drive the input selections
        resultName - The result that should be returned (instead of the full configurator results map)
        Returns:
        The result of the configurator
      • configurator

        Object configurator​(String configuratorName,
                            String formulaName,
                            Object width,
                            Object height)
        Parameters:
        configuratorName - The name of the configurator, similar to other options' names
        formulaName - The name of the configurator formula which is used to drive the input selections
        width - The width of the configurator window. Can be a number (in pixels) or a percentage string.
        height - The height of the configurator window. Can be a number (in pixels) or a percentage string.
        Returns:
        The result of the configurator
      • inlineConfigurator

        Object inlineConfigurator​(String configuratorName,
                                  String formulaName)
        Parameters:
        configuratorName - The name of the configurator, similar to other options' names
        formulaName - The name of the configurator formula which is used to drive the input selections
        Returns:
        The result of the configurator
      • parseDateTime

        DateTime parseDateTime​(String pattern,
                               String datetime)
        Parses a datetime (entered as a String) according to the given pattern.

        Important note: This method will use the UTC time zone for parsing (unless the provided pattern uses a syntax explicitly specifying a time zone). If a different time zone is required, use the parseDateTime(String, String, int, int) method which allows to set a time zone by providing an offset to UTC in hours and minutes.

        Example:

         def now = api.parseDateTime("yyyy-MM-dd'T'HH:mm:ss", "2019-01-23T13:44:52")
         now.getYear()            // 2019
         now.getMonthOfYear()     // 1
         now.getDayOfMonth()      // 23
         now.getHourOfDay()       // 13
         now.getMinuteOfHour()    // 44
         now.getSecondOfMinute()  // 52
         
        Parameters:
        pattern - The pattern for parsing (see DateTimeFormat for pattern format specification)
        datetime - The datetime as a String in the format specified by the pattern
        Returns:
        The datetime
        See Also:
        parseDate(String, String), parseDateTime(String, String, int, int)
      • parseDateTime

        DateTime parseDateTime​(String pattern,
                               String datetime,
                               int tzHoursOffset,
                               int tzMinutesOffset)
        Parses a datetime (entered as a String) according to a given pattern and time zone.

        Important note: This method will always use the provided time zone, regardless of the possible time zone set explicitly in datetime.

        Parameters:
        pattern - The pattern for parsing (see DateTimeFormat for pattern format specification)
        datetime - The datetime as a String in the format specified by the pattern
        tzHoursOffset - The offset in hours from UTC, from -23 to +23
        tzMinutesOffset - The offset in minutes from UTC, from -59 to +59
        Returns:
        The datetime
        See Also:
        parseDateTime(String, String), parseDate(String, String)
      • createElementNameFilter

        Filter createElementNameFilter​(String elementName,
                                       Object fieldValue,
                                       String... listTypedIds)
        Creates a cross-list filter expression based on meta data. Example: You need to filter across multiple price lists on items that have the value "A" in the column with the elementName "XYZ". Now the elementName XYZ might be mapped to a different attributeXX column for every list. So a simple attributeXX=A filter does not work. This method does a metadata lookup and creates a proper filter clause based on it for every list. For every list this translates into something like: (attributeXX = A AND listId = <id>) These filters are ORed together.
        Parameters:
        elementName - The element name (originates from the logic element name or MPL integration tag)
        fieldValue - The value (= operator applied) of that attribute
        listTypedIds - A list of typedId of the "header" objects. E.g. 34.PL. Supported type codes are PL, MPL, PG and SIM
        Returns:
        The filter object
      • getItemCompleteCalculationResults

        Map<String,​Object> getItemCompleteCalculationResults​(String typedId)
        Gets the current complete calculation results of the given item (e.g., price list item).

        Note: These are not returned when using other methods (e.g., pricelistItem(String, String)).

        Parameters:
        typedId - The typedId of the item, e.g. 34.PLI. Supported type codes are PLI, XPLI, SIMI, XSIMI, PGI, XPGI and RR
        Returns:
        The map of individual calculation results with 'Element Name' as the key
      • getItemActiveCalculationResults

        Map<String,​Object> getItemActiveCalculationResults​(String typedId)
        Gets the current complete active (i.e. approved) calculation results of the given item.
        Parameters:
        typedId - The typedId of the item, e.g. 34.PLI. Supported type codes are PGI and XPGI
        Returns:
        The map of individual calculation results with 'Element Name' as the key
      • httpCall

        Object httpCall​(String url,
                        String body)
                 throws XExpression
        Issues an HTTP call to an external entity. Defaulting to POST request and JSON content type. Arbitrary addresses/URLs are allowed with the exception of internal addresses (in particular xxx.pricefx.net hosts are blacklisted for security reasons). If called from a logic element, it has the same timeout as defined for that element.
        Parameters:
        url - The full URL to the HTTPS or HTTP endpoint
        body - The body of the request
        Returns:
        A map containing two elements 'responseBody' and 'errorCode'. If the content type is JSON and data is returned, responseBody will actually also be a parsed Map and not the raw data.
        Throws:
        XExpression - If the HTTP call fails
        See Also:
        httpCall(String, String, String, String, Map[])
      • boundCall

        Object boundCall​(String uniqueName,
                         String relativeUrl,
                         String body,
                         Boolean... responseBodyAsAString)
                  throws XExpression
        Triggers a HTTPS request towards the Pricefx server, either local one or an external one. Arbitrary addresses/URLs are allowed with the exception of internal addresses (in particular xxx.pricefx.net hosts are blacklisted for security reasons). If this method is called from a logic element, it has the same timeout as defined for that element. To be able to use this function, you need to set up a bound partition first in Configuration > All Modules > Bound Partitions.

        Example:

        
         def items = ...
         def requestBody = []
         items.each { item ->
        
             def record = [
                 "name": "Increase",
                 "sku": item.sku,
                 "attribute1": item.newValue,
             ]
        
             requestBody.add([
                 data: record,
                 oldValues: [:]
             ])
         }
         def resp = api.boundCall("localhost", "/integrate/PX/batch", api.jsonEncode(requestBody), true)
         
        Parameters:
        uniqueName - The unique name of the bound partition
        relativeUrl - The relative URL to the Pricefx server command. First slash excluded.
        body - The body of the request
        responseBodyAsAString - If the first param is true, the body is not converted to JSON but returned as a String
        Returns:
        A map containing two elements 'responseBody' and 'errorCode'
        Throws:
        XExpression - If the bound partition is not set or the call fails
        See Also:
        Pricefx backend API
      • getBoundPartitionNames

        Object getBoundPartitionNames()
        Returns a bound partition list.
        Returns:
        The bound partition unique names
      • httpCall

        Object httpCall​(String url,
                        String body,
                        String methodType,
                        String contentType,
                        Map... properties)
                 throws XExpression
        Issues an HTTP call to an external entity. If called from a logic element, it has the same timeout as defined for that element.
        Parameters:
        url - The full URL to the HTTPS or HTTP endpoint
        body - The body of the request
        methodType - "GET" or "POST"
        contentType -
        • "JSON" - JSON response will be deserialized into map
        • "APPLICATION_XML" (or "XML" (deprecated)) for contentType "application/xml"
        • "TEXT_XML" for contentType "text/xml"
        • or any full content type, for instance "text/plain"
        For XML content types, the response is GPath expressions can be used to work with it.
        properties - The map of properties. The following are allowed:
        • basicAuthenticationUserName String value - User name for basic authentication
        • basicAuthenticationPassword String value - User password for basic authentication
        • sslTrustAllCertificates boolean value - Ignores invalid certificates. Use for testing HTTPS connections only. Not for production use.
        • proxyAuthenticationUserName String value - User name for proxy (if any)
        • proxyAuthenticationPassword String value - User password for proxy (if any)
        • proxyUrl String value - Full URL to proxy
        • additionalHeaders Map value - Sub-map that will then add these headers verbatim to the request
        Returns:
        A map containing two elements 'responseBody' and 'statusCode'
        Throws:
        XExpression - If the HTTP call fails
      • add

        Object add​(String typeCode,
                   Map<String,​Object> values)
        Adds a new object to the collection of objects of the given type.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). This method cannot be used in distributed calculation.

        • CFS
        • CalculationFlow
        • direct formula execution via JSON API
        If any of the attributes is null, the record will not be updated. If you want a certain attribute to have a null value, do it explicitly, by putting e.g. the “NULL” marker value there or a similar one.

        Example 1:

         def entry = [
                 lookupTableName : "ExchangeRates",
                 key1 : "USD",
                 key2 : "EUR",
                 attribute1 : 0.879
         ]
         api.add("MLTV2", entry)
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        values - The key-value pairs representing fields of the object you want to add. Note that all significant fields have to be present.
        Returns:
        The added object or null if error occurred
        See Also:
        addOrUpdate(String, Map), update(String, Map), delete(String, Map)
      • addOrUpdate

        Object addOrUpdate​(String typeCode,
                           Map<String,​Object> values)
        Adds or updates an object in the collection of objects of the given type.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). This method also works with the Post Step Logic Formula in workflows. This method cannot be used in distributed calculation.

        Example 1:

         def entry = [
                 lookupTableName : "ExchangeRates",
                 key1 : "USD",
                 key2 : "EUR",
                 attribute1 : 0.879
         ]
         api.add("MLTV2", entry)
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        values - The key-value pairs representing fields of the object you want to add or update. Note that all significant fields have to be present.
        Returns:
        The object added or updated
        See Also:
        add(String, Map), update(String, Map), delete(String, Map)
      • update

        Object update​(String typeCode,
                      Map<String,​Object> values)
        Updates an object in the collection of objects of the given type.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). This method cannot be used in distributed calculation.

        Example 1:

         api.addOrUpdate("PX", [
                        "name": "Scoring_MM",
                        "sku": sku
         ])
         
        Example 2:
         api.addOrUpdate("PGI", [
                        "priceGridName" : "LifeCycleMonitor",
                        "sku"           : currentItem.sku,
                        "label"         : currentItem.label
         ])
         
        Example 3:
         def large = [
                        "lookupTableId"   : pp.id,
                        "lookupTableName" : pp.uniqueName,
                        "name"            : "L",
                        "attribute1"      : percentileHigh,
                        "attribute2"      : "999999999"
         ]
         api.addOrUpdate("MLTV", large)
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        values - The key-value pairs representing fields of the object you want to update. Note that all significant fields have to be present.
        Returns:
        The updated object or null if error occured
        See Also:
        addOrUpdate(String, Map), add(String, Map), delete(String, Map)
      • delete

        Object delete​(String typeCode,
                      Map<String,​Object> values)
        Deletes an object in the collection of objects of the given type.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). This method cannot be used in distributed calculation.

        Example:

         api.delete("PX", ["id": existingRecord, "name": "ActivePrice"])
         
        Parameters:
        typeCode - A type code string of the type of the object to search for. All available type codes can be retrieved by calling <hostname>/pricefx/<partition name>/fetch
        values - The key-value pairs representing significant fields of the object you want to delete. Note that all significant fields have to be present, if not the ID has to be present
        Returns:
        The deleted object or null if error occured
        See Also:
        addOrUpdate(String, Map), add(String, Map), update(String, Map)
      • sendEmail

        void sendEmail​(String to,
                       String subject,
                       String message)
        Sends an email. Only one recipient can be defined.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API).

        Example:

         def message = "The cost is missing"
         def filter = Filter.equals("name", "Costs")
        
         api.findLookupTableValues("EmailNotifications", filter).each {
             api.sendEmail(it.value, "Missing costs", message)
         }
         
        Parameters:
        to - The email address the email is sent to
        subject - The email subject
        message - The email body
      • sendEmail

        void sendEmail​(String to,
                       String toName,
                       String subject,
                       String message,
                       String fromEmail,
                       String fromName,
                       String replyToEmail,
                       String replyToName,
                       Boolean useCustomSMTP)
        Sends an email. Only one recipient can be defined.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API).

        Parameters:
        toEmail - The email address the email is sent to
        toName - The name of the recipient. If not specified then toEmail is used.
        subject - The email subject
        message - The email body
        fromEmail - The sender email address
        fromName - The name of the sender. If not specified then fromEmail is used.
        replyToEmail - The reply to email address
        replyToName - The reply to user name. If not specified then replyToEmail is used.
        useCustomSMTP - True if should be send through custom SMTP server.
      • customEvent

        void customEvent​(Object object)
        Sends an event of the type "CUSTOM". Other event types are reserved internally.

        Note: This operation will only work in contexts that allow object modification (CFS, CF and direct formula execution via JSON API). To enable sending of this type of events, this needs to be enabled on the Partition by the system admin (event type "CUSTOM" in the Event Bitmask).

        Parameters:
        object - The object to pass along with the event
      • customEvent

        void customEvent​(Object object,
                         String customEventType)
        Sends an event of the type "CUSTOM". Other event types are reserved internally.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). To enable sending of this type of events, this needs to be enabled on the Partition by the system admin (event type "CUSTOM" in the Event Bitmask).

        Parameters:
        object - The object to pass along with the event
        customEventType - A custom string to classify the custom event type (as the general event type is always CUSTOM)
      • customEvent

        void customEvent​(Object object,
                         String customEventType,
                         String operation)
        Sends an event of the type "CUSTOM". Other event types are reserved internally.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). To enable sending of this type of events, this needs to be enabled on the Partition by the system admin (event type "CUSTOM" in the Event Bitmask).

        Parameters:
        object - The object to pass along with the event
        customEventType - A custom string to classify the custom event type (as the general event type is always CUSTOM)
        operation - One of these strings: UPDATE, DELETE, ADD, ITEMCHANGE
      • customEvent

        void customEvent​(Object object,
                         String customEventType,
                         String operation,
                         boolean omitNullValues)
        Sends an event of the type "CUSTOM". Other event types are reserved internally.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API). To enable sending of this type of events, this needs to be enabled on the Partition by the system admin (event type "CUSTOM" in the Event Bitmask).

        Parameters:
        object - The object to pass along with the event
        customEventType - A custom string to classify the custom event type (as the general event type is always CUSTOM). Can be null.
        operation - One of these strings: UPDATE, DELETE, ADD, ITEMCHANGE. Can be null.
        omitNullValues - Also includes keys that have a null value (false) or omits them (true). True is the default for other method signatures that do not explicitly specify that value.
      • updateCalculableObjectHeader

        Object updateCalculableObjectHeader​(String calcObjTypeCode,
                                            String calcObjName)
        Updates the header information of a CalculableObject (e.g., a price grid, a price list, etc.).

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct formula execution via JSON API).

        Parameters:
        calcObjTypeCode - The type code of the object to update
        calcObjName - The (numeric) ID of the object to update
        Returns:
        The calculable Object Header
      • attributedResult

        AttributedResult attributedResult​(Object result)
        Creates an AttributedResult object to be returned as a result of an output element.

        Since AttributedResult is configurable, it is used when it is not sufficient to only return a plain value, but it is also required to adjust formatting, e.g. color, underline, etc.

        The usage is simple, instead of returning the output value, create a new AttributedResult instance like this: api.attributedResult(plain value), customize it by calling its various methods, and return it finally.

        Example:

        
         def cost = api.getElement("Margin_pct")
         return api.attributedResult(cost)
         .withBackgroundColor(cost < 0.30 ? "red" : "#0101DF")
         .withSuffix(cost < 0.30 ? "!!!" : null)
         .withTextColor(cost < 0.30 ? "white" : null)
         .withTextDecoration(cost < 0.30 ? "underline" : null)
         
        Parameters:
        result - The calculation result
        Returns:
        The AttributedResult object
        See Also:
        AttributedResult - for details on formatting
      • wrap

        WrappedResult wrap​(Object result)
        Wraps a result to make sure the original result object appears in the JSON response. This way also more complex results like lists and maps can be exported as a logic element result.
        Parameters:
        result - The result
        Returns:
        A wrapped result object. Should only be used as a return statement of a logic element.
      • newMatrix

        ResultMatrix newMatrix()
        Creates a new result matrix DTO object that can be further customized and populated with calculated data.
         The individual cells can be styled via the use of:
         -  linkCell(Object value, String targetPage, String targetPageState)
         -  imageCell(Object imageUrl)
         -  styledCell(Object value, String textColor, String bgColor, String weight, String alignment)
         -  styledCell(Object value, String textColor, String bgColor, String weight)
         -  styledCell(Object value, String textColor, String bgColor)
         -  setColumnFormat(String column, FieldFormatType fft)
        
         Valid FieldFormatTypes are:
         NUMERIC, NUMERIC_LONG, MONEY, PERCENT, TEXT, MONEY_EUR, MONEY_USD, MONEY_GBP, MONEY_JPY, MONEY_CHF, MONEY_PLN, DATETIME, DATE, INTEGER
         

        Example:

        
         def getTrafficColor(value) {
             if (value <= 0) {
                 return "red"
             } else if (value > 0 && value < 0.1) {
                 return "yellow"
             } else if (value >= 0.1) {
                 return "green"
             }
         }
        
         // initialize new matrix with three columns
         def matrix = api.newMatrix("Item", "Quantity", "Price", "Pricegrid", "Pricelist", "Margin Status", "Image", "CustomerId")
        
         // add more columns dynamically
         matrix.addColumn("Margin %")
         matrix.addColumn("Url")
        
         // set column formats
         matrix.setColumnFormat("Item", FieldFormatType.TEXT)
         matrix.setColumnFormat("Quantity", FieldFormatType.NUMERIC_LONG)
         matrix.setColumnFormat("Price", FieldFormatType.MONEY_EUR)
         matrix.setColumnFormat("Margin %", FieldFormatType.PERCENT)
         matrix.setColumnFormat("Url", FieldFormatType.LINK)
        
         // allow users to filter values
         matrix.setEnableClientFilter(true)
        
         // add data row
         matrix.addRow([
                 "Item": matrix.styledCell("Red bold text", "#ff0000", "transparent", "bold"),
                 "Quantity": 1.23456,
                 "Price": 78.9012,
                 "Margin %": 0.3456,
        
                 "Url": "<a href=\"https://www.google.com/search?q=price+f(x)\">link</a>",
        
                 // optionally you can add link to a price grid of a given ID
                 "Pricegrid" : matrix.linkToPriceGrid("Open Pricegrid", 123, null),
        
                 // or to a price list of a given ID
                 "Pricelist" : matrix.linkToPriceList("Open Pricelist", 123, null),
        
                 // or a to custom page (result identical to the previous)
                 "CustomerId" : matrix.linkCell("Open Customer", "customersPage", "123456"),
        
                 // or add a library images, such as Traffic, BlackTraffic or Arrow
                 "Margin Status" : matrix.libraryImage("BlackTraffic", getTrafficColor(-0.2f)),
        
                 // or add a general image
                 "Image" : matrix.imageCell("images/grid/approve.png"),
         ])
        
        
         return matrix
         
        Returns:
        ResultMatrix object
        See Also:
        newMatrix(String...)
      • newMatrix

        ResultMatrix newMatrix​(String... columns)
        Creates a new result matrix DTO object that can be further customized and populated with calculated data. See the documentation in newMatrix().
        Parameters:
        columns - The initial set of columns for the result matrix
        Returns:
        The ResultMatrix object
        See Also:
        newMatrix()
      • newMatrix

        ResultMatrix newMatrix​(Collection<String> columns)
        Creates a new result matrix DTO object that can be further customized and populated with calculated data. See the documentation in newMatrix().
        Parameters:
        columns - The initial set of columns for the result matrix
        Returns:
        The ResultMatrix object
        See Also:
        newMatrix(String...), newMatrix()
      • newGauge

        ResultGauge newGauge()
        Creates a new gauge object that can be further customized.

        Example:

         def gauge = api.newGauge()
         gauge.addSector(5, "#FF0000")
         gauge.addSector(25, "#FFFF00")
         gauge.addSector(null, "#00FF00")
         gauge.setValue(10)
         
        Returns:
        the ResultGauge object
      • newController

        DashboardController newController()
        Creates a new dashboard controller object that can be further customized.

        Example:

        
         def lookupTable = api.findLookupTable("SalesOrg")
         def controller = api.newController()
         controller.addButton("1. STEP: Change Price Strategy", "pricingParametersPage", lookupTable.typedId)
         controller.addHTML("<h2>Meatball</h2>")
         
        Returns:
        the DashboardController object
      • walkFilter

        Filter walkFilter​(Filter filter,
                          Closure<?> visitBefore,
                          Closure<?> visitAfter,
                          boolean removeNulls)
        Walks a filter and all its sub filters, visiting each filter in the tree. A pair of closures is used to visit each filter. Each closure can replace the Filter that is visiting. If it does, a new tree will be created for every part of the tree that is affected, thus preserving the original tree. removeNulls is consulted only in case of (sub)filters which take a list of sub-filters.

        Hence, this method may be used in many cases. For instance, you can use it for mapping the current property set to another one, e.g. to convert a PB filter to a PA one. Similarly to this example:

        
         def propertyMappings = ["sku": "ProductID"]
        
         api.walkFilter(pbFilter, null, { filter ->
             if (filter != null && propertyMappings[filter.property] != null) {
                 filter.property = propertyMappings[filter.property]
             }
             filter
         }, false);
         
        Parameters:
        filter - The filter object
        visitBefore - The before closure
        visitAfter - The after closure
        removeNulls - Removes nulls
        Returns:
        If any changes have been made, the new Filter; if not, the original Filter.
      • findDataLoad

        Object findDataLoad​(String dataLoadLabel,
                            String dataLoadType,
                            String target)
        Parameters:
        dataLoadLabel - The label of DMDataLoad as seen in the Data Load UI
        dataLoadType - The load type of DMDataLoad as seen in the Data Load UI. Namely:
        • Customers
        • Products
        • Flush
        • Calendar
        • Refresh
        • Calculation
        • Truncate
        • Simulation
        • ModelCalculation
        • InternalCopy
        • IndexMaintenance
        target - The target of DMDataLoad as seen in the Data Load UI
        Returns:
        The Data Load if and only if there is exactly one Data Load matching (fail early strategy)
      • findRebateRecordLoad

        Object findRebateRecordLoad​(String rebateRecordLoadLabel)
        Parameters:
        rebateRecordLoadLabel - The label of the rebate record load as seen in the Rebate Record UI
        Returns:
        The rebateRecordLoad if and only if there is exactly one load matching (fail early strategy)
      • currentPartitionName

        String currentPartitionName()
        Returns the current partition name.
        Returns:
        The partition name
      • getTimeZone

        DateTimeZone getTimeZone​(String tzString)
        Provides a wrapper for org.joda.time.DateTimeZone.forId(String tzString) method. For details see their documentation.

        Example 1:

         def timezone1 = api.getTimeZone("Europe/Berlin")
         def timezone2 = api.getTimeZone("Europe/Prague")
         def timezone3 = api.getTimeZone("America/New_York")
         def timezone4 = api.getTimeZone("Australia/Brisbane")
         

        Example 2:

         def startHour = 20
         def offset = api.getTimeZone("Europe/Prague").getOffset(new Date().getTime())
         def startHourUTC = startHour - offset.intValue()
         
        Parameters:
        tzString - The timezone String
        Returns:
        The DateTimeZone object
        See Also:
        https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
      • uuid

        String uuid​(int len)
        Generates a random uuid of the specified length.

        Example:

         return uuid(15)   // returns e.g. "VcydxgltxrVZSTV"
         
        Parameters:
        len - The desired number of characters
        Returns:
        The uuid string
      • uuid

        String uuid​(int len,
                    int radix)
        Generates a random uuid of the specified length and radix.

        Examples:

         return uuid(8, 2) // returns e.g. "01001010" (8 character ID, base=2)
        
         return uuid(8, 10)       // returns e.g. "47473046" (8 character ID, base=10)
        
         return uuid(8, 16)       // returns e.g. "098F4D35" (8 character ID, base=16)
         
        Parameters:
        len - The desired number of characters
        radix - The number of allowable values for each character (must be <=62)
        Returns:
        The uuid string
      • uuid

        String uuid()
        Generates a RFC4122, version 4 ID.

        Example:

         return api.uuid()   // returns e.g. "92329D39-6F5C-4520-ABFC-AAB64544E172"
         
        Returns:
        The uuid string
      • multiKey

        MultiKey<Object> multiKey​(Object... keys)
        Constructs a new composite key object which can be used as a key in a map. Equality of two keys is defined by the pair-wise equality of the corresponding key values.
        Parameters:
        keys - Key values
        Returns:
        MultiKey composed of the passed ordered key values
      • roles

        Map<String,​String> roles()
        Lists all roles available in the application.
        Returns:
        Map of [roleUniqueName : roleLabel] pairs
      • entityRef

        String entityRef​(PartitionedObject po)
                  throws IllegalAccessException
        Creates an entityRef value (usually db ID) for the given entity. The value can be stored in attributeXX fields and you can set its meta type to ENTITY REFERENCE if you want the UI to show the data as links.
        Parameters:
        po - The object of a typedCode P, C, DCR, Q, CT, RBA
        Returns:
        The string that represents the linkable state of the entity
        Throws:
        IllegalAccessException - If po is of a different typeCode
      • evalExpression

        double evalExpression​(String mathExpression)
        Evaluates an arithmetic expression that is passed as a String. Supported operations are:
        • addition +
        • subtraction -
        • multiplication *
        • division /
        • exponentiation ^
        • square root sqrt
        Operator precedence and associativity rules are respected.

        Example:

         evalExpression("((10 - 3^2 + 1) * -sqrt(1 * 2 + 3 * 4)) / 4")
         
        Parameters:
        mathExpression - The mathematical expression
        Returns:
        The result of the expression as double
      • getSharedCache

        String getSharedCache​(String key)
        Retrieves a value from the shared cache (and resets the TTL of the key).
        Parameters:
        key - The cache key
        Returns:
        The value or null found in the shared cache
        See Also:
        getSharedCache(String)
      • getProductReferences

        List<?> getProductReferences​(String typeCode,
                                     Set<String> skus)
        Returns a list of product reference records that tell which other objects, of the given type, reference these SKUs.
        Parameters:
        typeCode - Currently, only "Q" or "RBA" are supported
        skus - A set of SKU strings that should be searched for
        Returns:
        A list of reference records
      • getSkusFromProductGroup

        List<String> getSkusFromProductGroup​(ProductGroup pg)
        Returns a list of SKUs based on the definition of the product group
        Parameters:
        pg - The product group object
        Returns:
        List of SKU
      • getCustomerIdsFromCustomerGroup

        List<String> getCustomerIdsFromCustomerGroup​(CustomerGroup cg)
        Returns a list of Customer IDs based on the definition of the customer group
        Parameters:
        cg - The customer group object
        Returns:
        List of customer IDs
      • getLocale

        String getLocale()
        Returns the language part of the current request's locale (e.g. "en").
        Returns:
        The language part string
      • getBaseURL

        String getBaseURL()
        Returns the base URL component of the current instance. Example: https://www.pricefx.eu

        Example:

         api.getBaseURL() // "https://www.pricefx.eu"
         
        Returns:
        The base URL
      • newCreationWorkflow

        CreationWorkflowDefinition newCreationWorkflow()
      • newCreationWorkflowStep

        CreationWorkflowStepDefinition newCreationWorkflowStep()
      • findNextRevUNs

        Map<String,​List<String>> findNextRevUNs​(String typeCode,
                                                      String... uniqueNames)
        Finds the next revision uniqueNames for the given Quotes/Contracts/RebateAgreements.
        Parameters:
        typeCode - Can be one of: 'Q', 'CT', 'RBA'
        uniqueNames - List of uniqueNames
        Returns:
        Map of [uniqueName : List of nextRevUNs]
      • getClaimContext

        ClaimContext getClaimContext()
        Gives current item context in claim validation
        Returns:
        Claim Context instance
      • isFullListCalculation

        Boolean isFullListCalculation()
        Indicates whether the current calculation is recalculating the entire list or only parts of it.

        Note: Currently only applicable for price grid calculations.

        Returns:
        True if the entire grid is calculated, false otherwise. null is returned if method is not applicable
      • triggerPriceGridCalculation

        Long triggerPriceGridCalculation​(Long priceGridId,
                                         Map<String,​Object> parameters)
        Creates a new background calculation job for the specified price grid. Either a full calculation (parameters == null) or a partial calculation (parameter entry "skusToRecalc" as a list of SKU strings).

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct logic execution via JSON API).

        Parameters:
        priceGridId - The ID of the price grid to calculate
        parameters - Optional job parameters
        Returns:
        The ID of the created job tracker
      • triggerCFSCalculation

        Long triggerCFSCalculation​(Long cfsID)
        Creates a new background calculation job for the specified CFS.

        Note: This operation will only work in contexts that allow object modification (CFS, CalculationFlow and direct logic execution via JSON API).

        Parameters:
        cfsID - The ID of CalculatedFieldSet
        Returns:
        The ID of the created job tracker
      • currentContext

        Map currentContext()
        Provides a Map of current execution context info variables.

        Currently supported variables are:

        • commandName Command name (if any) that was used to invoke current logic execution, e.g. "addproducts", "save", "price", "submit", "calculate"
        Returns:
        the context map
      • resetCurrentItemFields

        void resetCurrentItemFields​(String... fields)
        Resets specified fields on currentItem object to null. Applies only to price grid items. Fields that can not be found on the item are skipped.
        Parameters:
        fields - field names that should be reset
      • evalProductFilterLogic

        List<Filter> evalProductFilterLogic​(String logicName,
                                            String logicParam)
        Evaluates product(group) filter logic
      • evalCustomerFilterLogic

        List<Filter> evalCustomerFilterLogic​(String logicName,
                                             String logicParam)
        Evaluates customer(group) filter logic
      • createOrUpdatePricegridInputAttribute

        Object createOrUpdatePricegridInputAttribute​(String fieldName,
                                                     String elementName,
                                                     String label,
                                                     Long priceGridId)
        Creates or updates user input attribute on LPG.

        Note: Input attributes are saved to extension columns (like attribute12 for example) - same as output elements. Please consider this so that you do not accidentally overwrite any existing output element.

        Parameters:
        fieldName - Name of field to be used for storing values, e.g. attribute12
        elementName - Name of the column, e.g. colour
        label - Label of the column, e.g. Colour
        priceGridId - pricegrid id which can usually be obtained by using api.currentItem("id")
        Returns:
        Created or updated attribute
      • removePricegridInputAttribute

        Object removePricegridInputAttribute​(Long id)
        Deletes a pricegrid input attribute.
        Parameters:
        id - Id of the input attribute to delete
        Returns:
        The deleted attribute object or null if no attrbiute was found
      • createOrUpdatePricelistInputAttribute

        Object createOrUpdatePricelistInputAttribute​(String fieldName,
                                                     String elementName,
                                                     String label,
                                                     Long pricelistId)
        Creates or updates user input attribute on PL.

        Note: Input attributes are saved to extension columns (like attribute12 for example) - same as output elements. Please consider this so that you do not accidentally overwrite any existing output element.

        Parameters:
        fieldName - Name of field to be used for storing values, e.g. attribute12
        elementName - Name of the column, e.g. colour
        label - Label of the column, e.g. Colour
        priceGridId - pricegrid id which can usually be obtained by using api.currentItem("id")
        Returns:
        Created or updated attribute
      • removePricelistInputAttribute

        Object removePricelistInputAttribute​(Long id)
        Deletes a pricelist input attribute.
        Parameters:
        id - Id of the input attribute to delete
        Returns:
        The deleted attribute object or null if no attrbiute was found
      • setPricegridCalculationOutput

        Object setPricegridCalculationOutput​(Long pricegridId,
                                             String name,
                                             String label,
                                             String value,
                                             String message)
        Sets PG calculation output that will be shown in the header section after PG calculation.
        Parameters:
        pricegridId - pricegrid id which can usually be obtained by using api.currentItem("id")
        name - name of the calculation output, e.g. sales
        label - label of the calculation output, e.g. Global Sales
        value - calculated value, e.g. €2.3M
        message - message containing additional information
        Returns:
        saved calculation output
      • removePricegridCalculationOutput

        void removePricegridCalculationOutput​(Long pricegridId,
                                              String name)
        Removes PG calculation output.
        Parameters:
        pricegridId - pricegrid id which can usually be obtained by using api.currentItem("id")
        name - name of the calculation output that will be removed
      • setPricegridCalculationChart

        Object setPricegridCalculationChart​(Map<String,​?> definition,
                                            Long pricegridId)
        Chart definition that will be used to construct and display a Highchart in the header section.
        Parameters:
        definition - highchart definition as a map
        pricegridId - pricegrid id which can usually be obtained by using api.currentItem("id")
        Returns:
        saved chart definition
      • setPricelistCalculationOutput

        Object setPricelistCalculationOutput​(Long pricelistId,
                                             String name,
                                             String label,
                                             String value,
                                             String message)
        Sets PL calculation output that will be shown in the header section after PL calculation.
        Parameters:
        pricelistId - pricelist id which can usually be obtained by using api.currentItem("id")
        name - name of the calculation output, e.g. sales
        label - label of the calculation output, e.g. Global Sales
        value - calculated value, e.g. €2.3M
        message - message containing additional information
        Returns:
        saved calculation output
      • removePricelistCalculationOutput

        void removePricelistCalculationOutput​(Long pricegridId,
                                              String name)
        Removes PL calculation output.
        Parameters:
        pricelistId - pricelist id which can usually be obtained by using api.currentItem("id")
        name - name of the calculation output that will be removed
      • setPricelistCalculationChart

        Object setPricelistCalculationChart​(Map<String,​?> definition,
                                            Long pricegridId)
        Chart definition that will be used to construct and display a Highchart in the header section.
        Parameters:
        definition - highchart definition as a map
        pricelistId - pricelist id which can usually be obtained by using api.currentItem("id")
        Returns:
        saved chart definition