Interface PublicGroovyAPI
-
public interface PublicGroovyAPI
This interface represents what can be reached in the Groovy element syntax asapi
. Thatapi
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 Summary
All Methods Instance Methods Abstract Methods Deprecated Methods Modifier and Type Method Description void
abortCalculation()
Aborts the current item calculation.void
abortCalculation(boolean keepOld)
Aborts the current item calculation.Object
add(String typeCode, Map<String,Object> values)
Adds a new object to the collection of objects of the given type.Object
addOrUpdate(String typeCode, Map<String,Object> values)
Adds or updates an object in the collection of objects of the given type.void
addWarning(String message)
Adds a warning to the formula execution warning log.Object
anyUser(String entryName)
Creates an input parameter that lets the user select a user from the list of all users.AttributedResult
attributedResult(Object result)
Creates anAttributedResult
object to be returned as a result of an output element.String
base64Decode(String base64String)
Decodes a base64 encoded string.String
base64Encode(String string)
Provides a standard Base64 encoding of a string.Object
bom()
Accesses and retrieves values from a rolled-up bill of materials for the SKU being calculated.Object
bom(String lookupTableName)
Accesses and retrieves values from a rolled-up bill of materials for the SKU being calculated.Object
bom(String lookupTableName, String categoryName)
Accesses and retrieves values from a rolled-up bill of materials for the SKU being calculated.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.Object
bomList()
Rolls up the current SKU's BoM and returns the rolled up BoM records (not just the quantities).Object
booleanUserEntry(String entryName)
Creates an input parameter that lets the user enter a boolean (yes or no) value.Object
boundCall(String uniqueName, String relativeUrl, String body, Boolean... responseBodyAsAString)
Triggers a HTTPS request towards the Price fx server, either local one or an external one.ResultFlexChart
buildFlexChart(Object definition)
Deprecated.CallsbuildFlexChart(null, definition)
See the full documentation inbuildFlexChart(Object)
.ResultFlexChart
buildFlexChart(String baseTemplateToUse, Object definition)
Deprecated.Creates aFlexChart
from the passeddefinition
by merging it withoptions
defined within thebaseTemplateToUse
template.ResultHighchart
buildHighchart(Map<String,?> definition)
Creates aResultHighchart
from the passeddefinition
.ResultHighmap
buildHighmap(Map<String,?> definition)
Creates aResultHighmap
from the passeddefinition
.Calendar
calendar()
Gets ajava.util.Calendar
object initialized with the current targetDate (or new Date() if no target date is given).Calendar
calendar(Date date)
Gets a calendar object initialized withdate
.Object
configurator(String configuratorName, String formulaName)
Object
configurator(String configuratorName, String formulaName, Object resultName)
Object
configurator(String configuratorName, String formulaName, Object width, Object height)
Object
contextByLabel(String label)
Retrieves the previous calculation result by the logic element label (not the element result name).String
contextName()
The name of the current context, e.g.Set<Object>
contextSkuSet(int startRow)
Returns a set of SKUs which comprise so-called 'SKU context' of the current formula execution.String
contextType()
The type (type code string) of the current context.String
contextTypedId()
The typedId of the current context.int
count(String typeCode, Filter... filters)
Returns the number of records that a correspondingfind(String, int, int, String, List, Filter...)
would return.ConfiguratorEntry
createConfiguratorEntry()
Creates an empty configurator entry object.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.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.ConfiguratorEntryArray
createConfiguratorEntryArray(Object... entries)
Creates a configurator entry array object which is to be returned from a logic element.Filter
createElementNameFilter(String elementName, Object fieldValue, String... listTypedIds)
Creates a cross-list filter expression based on meta data.Object
createNewRevision(String typedId)
Creates a revision of CalculableLineItemCollection (Quote, Rebate Agreement, Contract).Object
createOrUpdatePricegridInputAttribute(String fieldName, String elementName, String label, Long priceGridId)
Creates or updates user input attribute on LPG.Object
createOrUpdatePricelistInputAttribute(String fieldName, String elementName, String label, Long pricelistId)
Creates or updates user input attribute on PL.void
criticalAlert(String msg)
Marks the current logic element as a critical alert and provides the given message.Map
currentContext()
Provides a Map of current execution context info variables.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.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.Object
currentItem()
In case of a list processing operation, this method gets the currently worked on record (e.g., price list item or price grid item or quote item).Object
currentItem(String attributeName)
Same ascurrentItem()
but returns only the specified attribute.Object
currentItemByElementName(String elementName)
In case of a list processing operation, this method gets the currently worked on record's property by elementName.String
currentPartitionName()
Returns the current partition name.Object
customer(String attributeName)
Retrieves the customer object for the SKU currently being calculated.Object
customer(String attributeName, boolean defaultFromParent)
Equivalent of the standard syntax "Customer" function.Object
customer(String attributeName, String customerId)
Retrieves the given attribute value from the customer table for the SKU being calculated.Object
customer(String attributeName, String customerId, boolean defaultFromParent)
Retrieves the given attribute value of the given 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 isnull
and defaultFromParent istrue
, retrieves (and returns) the value from the customer's parent regardless if that value isnull
as well or not.Object
customerExtension(String extensionName, Filter... filters)
Retrieves a list of all customer extentions records (CX) from a CX table namedextensionName
Object
customerGroupEntry(String... entryName)
Creates an input parameter that lets the user select a group of customers and returns the selection as a Map.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.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.void
customEvent(Object object)
Sends an event of the type "CUSTOM".void
customEvent(Object object, String customEventType)
Sends an event of the type "CUSTOM".void
customEvent(Object object, String customEventType, String operation)
Sends an event of the type "CUSTOM".void
customEvent(Object object, String customEventType, String operation, boolean omitNullValues)
Sends an event of the type "CUSTOM".Object
datamartCalendar()
Deprecated.UseDatamartContext.calendar()
instead.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.Object
datamartFilterBuilderUserEntry(String entryName, String source, Object... args)
Creates an input parameter that lets the user build a filter for a given Datamart.Object
datamartLookup(Object... queryAndProjectionsAndFilters)
Deprecated.UseDatamartContext.executeQuery(DatamartContext.Query)
,net.pricefx.formulaengine.DatamartContext#executeSqlQuery(String, DatamartContext.Query...)
orDatamartContext.streamQuery(DatamartContext.Query)
Object
datamartQuery(Object... queryAndDatamartAndProjectionsAndFilters)
Deprecated.Object
dateRangeUserEntry(String entryName)
Creates an input parameter that lets the user enter a date range (start and end date).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.Object
dateUserEntry(String entryName)
Creates an input parameter that lets the user enter a date value.Object
decimalUserEntry(String entryName)
Creates an input parameter that lets the user enter a decimal value.Object
delete(String typeCode, Map<String,Object> values)
Deletes an object in the collection of objects of the given type.boolean
emit(Object obj)
Emits an object to be consumed by an external thread.boolean
emitPersistedObject(String typedId)
Finds the PersistedObject with the given typedId and emits it if it exists.boolean
emitPersistedObject(String typeCode, Long id)
Finds the PersistedObject for the given type and ID and emits it if it exists.void
emitRebateRecords(String dateFieldName, String sortBy, Filter... filters)
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...).String
entityRef(PartitionedObject po)
Creates an entityRef value (usually db ID) for the given entity.List<Filter>
evalCustomerFilterLogic(String logicName, String logicParam)
Evaluates customer(group) filter logicdouble
evalExpression(String mathExpression)
Evaluates an arithmetic expression that is passed as a String.List<Filter>
evalProductFilterLogic(String logicName, String logicParam)
Evaluates product(group) filter logicObject
filter(String property, Object value)
Deprecated.UseFilter.equal(String, Object)
insteadObject
filter(String property, Object opString, Object value)
Deprecated.Use theFilter
functions insteadObject
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 bytypeCode
parameter.Filter
filterFromMap(Map<String,Object> filterMap)
Constructs a Filter object from the map representation of that filter (from the "wire format").List<Object>
find(String typeCode, int startRow, int maxRows, String sortBy, Filter... filters)
The Swiss army knife method of the API.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.List<Object>
find(String typeCode, int startRow, int maxRows, String sortBy, List<String> fields, Filter... filters)
The Swiss army knife method of the API.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.List<Object>
find(String typeCode, int startRow, Filter... filters)
Deprecated.usefind(String, int, int, String, List, Filter...)
because of performance you should always specify the fields to be returned.List<Object>
find(String typeCode, int startRow, String sortBy, Filter... filters)
Deprecated.usefind(String, int, int, String, List, Filter...)
because of performance you should always specify the fields to be returned.List<Object>
find(String typeCode, Filter... filters)
Deprecated.usefind(String, int, int, String, List, Filter...)
in order to always specify the fields to be returned because of performance.List<SummaryCalculableObjectItem>
findApprovedPricelistItems(String sku)
Returns a list of summary items.List<CalculatedFieldSet>
findCalculatedFieldSets(Date targetDate, String cfsName)
Returns a list of calculated field sets that match the targetDate.List<CustomerAssignment>
findCustomerAssignments(String customerId)
Finds all assignment records for the given customerId.List<Customer>
findCustomersInGroup(CustomerGroup group)
Retrieves a list of customers that match the given CustomerGroup (returns first 200 entries).List<Customer>
findCustomersInGroup(CustomerGroup group, int startRow, String sortBy)
Retrieves a list of customers that match the given CustomerGroup with custom paging and sorting.Object
findDataLoad(String dataLoadLabel, String dataLoadType, String target)
LookupTable
findLookupTable(String tableName)
Finds a price parameter table object (LT) of the given name.List<Object>
findLookupTableValues(String tableName, Filter... filters)
Returns all values of a named price parameter table (optionally filtered).List<ManualPricelist>
findManualPricelists(Date targetDate, String listName)
Returns a list of manual price lists that match the targetDate (i.e.Map<String,List<String>>
findNextRevUNs(String typeCode, String... uniqueNames)
Finds the next revision uniqueNames for the given Quotes/Contracts/RebateAgreements.Map<String,Object>
findPreviousApprovableState(String typedId, String... workflowStatuses)
Finds the previous approvable entity state if some DENIED or WITHDRAWN workflow for the approvable exists.WorkflowInfo
findPreviousWorkflowInfo(String typedId, String... workflowStatuses)
Finds the approvable entity previous workflow history if some DENIED or WITHDRAWN workflow for the approvable exists.List<PriceGrid>
findPriceGrids(Date targetDate, String priceGridName)
Returns a list of price grids that match the targetDate (i.e.List<Pricelist>
findPricelists(Date targetDate, String listName)
Returns a list of price lists that match the targetDate (i.e.Object
findRebateRecordLoad(String rebateRecordLoadLabel)
List<Simulation>
findSimulations(Date targetDate, String simulationName)
Returns a list of simulations that match the targetDate (i.e.WorkflowInfo
findWorkflowInfo(String approvableTypeCode, Object approvableId)
Finds active workflows for the given approvable.String
formatNumber(String pattern, Object n)
Formats a number as a String.String
formatNumber(String locale, String pattern, Object n)
Formats a number as a String.String
formatString(String locale, String format, Object... args)
Formats a string likeString.format(java.lang.String, java.lang.Object...)
.String
getBaseURL()
Returns the base URL component of the current instance.List<String[]>
getBatchInfo()
Gets the info about the current batch of items being calculated by a calcuation thread.Object
getBinding(String name)
Gets a named binding variable from a library function.Object
getBoundPartitionNames()
Returns a bound partition list.<T extends CalculableLineItem>
TgetCalculableLineItem(Object clic, String lineId)
Returns a line item of the given calculable line item collection (CLIC).Object
getCalculableLineItemCollection(String typedId)
Returns the full object (header and line items) of e.g.Object
getCalculableLineItemResult(Object cli, String... resultNamesOrLabels)
Returns results of the given names (or labels) from a line item object (its map representation).String
getCalculationContext()
Retrieves the CalculationContext of the logic evaluation (logic element group).
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 In RebateAgreement calculation there is: FORMULAELEMENTGROUP_RM_AGREEMENT = "agreement" FORMULAELEMENTGROUP_RM_AGREEMENT_READONLY = "agreementReadOnly" FORMULAELEMENTGROUP_RM_REBATERECORD = "rebateRecord" 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"ClaimContext
getClaimContext()
Gives current item context in claim validationDatamartContext
getDatamartContext()
Provides an API for querying and loading PA data.DatamartRowSet
getDatamartRowSet()
Available in a PA DataLoad context only, aDatamartRowSet
provides access to the rows being loaded or calculated.DatamartRowSet
getDatamartRowSet(String name)
Available in a PA DataLoad context only, aDatamartRowSet
provides access to the rows currently being loaded or calculated.Object
getElement(String name)
Gets the result of the previous logic element.Map<String,Object>
getGlobal()
A publicly available cache (as a hashmap) for storing and sharing values across logic elements.Long
getId(Object obj)
Returns the ID part of an object.Map<String,Object>
getItemActiveCalculationResults(String typedId)
Gets the current complete active (i.e.Map<String,Object>
getItemCompleteCalculationResults(String typedId)
Gets the current complete calculation results of the given item (e.g., price list item).int
getIterationNumber()
Returns the number of iterations this list has been calculated during this cycle.String
getLocale()
Returns the language part of the current request's locale (e.g.Object
getManualOverride(String elementName)
Returns a user entered value that overrides the calculated result of a logic element.int
getMaxFindResultsLimit()
Returns the maximum number of records thatfind(String, int, int, String, Filter...)
and its variations can return in one call.ContextParameter
getParameter(String parameterName)
Retrieves an already generated (in the previous logic step) input parameter in the form of aContextParameter
object.ItemSummaryQuery<PriceGrid>
getPriceGridSummaryQuery()
Creates a summary query object that can be parameterized and is then subsequently used inrunSummaryQuery(ItemSummaryQuery)
.Map<String,Object>
getPricelistItem(String listName)
Similar to thepricelistItem(String)
function.ItemSummaryQuery<Pricelist>
getPricelistSummaryQuery()
Creates a summary query object that can be parameterized and is then subsequently used inrunSummaryQuery(ItemSummaryQuery)
.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.Object
getProperty(Object object, String path)
Serves as an optimized way to get to certain object attributes.Object
getPropertyByElementName(Object object, String elementName)
Gets object attributes by elementName.ItemSummaryQuery<RebateRecordSet>
getRebateRecordSummaryQuery()
Creates a summary query object that can be parameterized and is then subsequently used inrunSummaryQuery(ItemSummaryQuery)
.Object
getSecondaryKey()
Same asapi.currentItem("key2")
.String
getSharedCache(String key)
Retrieves a value from the shared cache (and resets the TTL of the key).ItemSummaryQuery<Simulation>
getSimulationSummaryQuery()
Creates a summary query object that can be parameterized and is then subsequently used inrunSummaryQuery(ItemSummaryQuery)
.TableContext
getTableContext()
Provides an SQL query (SELECT only) interface to PA query results.DateTimeZone
getTimeZone(String tzString)
Provides a wrapper for org.joda.time.DateTimeZone.forId(String tzString) method.Object
httpCall(String url, String body)
Issues an HTTP call to an external entity.Object
httpCall(String url, String body, String methodType, String contentType, Map... properties)
Issues an HTTP call to an external entity.Object
inlineConfigurator(String configuratorName, String formulaName)
Object
input(String inputName)
Retrieves the value of the input parameter of the given name.Object
inputMatrix(String inputMatrixName, String... columnNames)
Creates an input parameter that lets the user select a matrix of values.Object
inputMatrix(String inputMatrixName, Map<String,Object> paramConfig, String... columns)
Creates an input parameter that lets the user select a matrix of values.Object
integerUserEntry(String entryName)
Creates an input parameter that lets the user enter an integer value.boolean
isDebugMode()
Returns true if the logic is called via the UI debug/test execution mode.boolean
isDistributedMode()
Returns true if the calculation is executed in the distributed mode.Boolean
isFullListCalculation()
Indicates whether the current calculation is recalculating the entire list or only parts of it.boolean
isSecondPass()
Deprecated.UsegetIterationNumber()
> 0 instead.boolean
isSyntaxCheck()
Returns true if the formula is executed in the syntax check mode.boolean
isUserInGroup(String userGroupName, String loginUserName)
Checks if the current user is a member of the given user group.Object
jsonDecode(String json)
A utility method to decode a JSON string into a Map representation.Object
jsonDecodeList(String json)
A utility method to decode a JSON string into a List representation.Object
jsonEncode(Object input)
A utility method to encode an object to a JSON string.Object
jsonEncode(Object input, boolean omitNull)
A utility method to encode an object to a JSON string.void
log(Object msg)
This function can be used by the support team only.void
log(String msg, Object arg1)
This function is meant to be used by the Pricefx internally only.void
logInfo(Object msg)
Logs a INFO message to the system error log which can be displayed in menu Tools / Logs / View Log.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.void
logWarn(Object msg)
Logs a WARN message to the system error log which can be displayed in menu Tools / Logs / View Log.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.void
markItemClean()
Removes the dirty flag from the current item set previously bymarkItemDirty()
.void
markItemClean(String sku)
Removes the dirty flag from the specified item set previously bymarkItemDirty(String)
.void
markItemClean(String sku, String key2)
Removes the dirty flag from the specified matrix item set previously bymarkItemDirty(String, String)
.void
markItemDirty()
Sets the dirty flag on the specified item, i.e.void
markItemDirty(String sku)
Sets the dirty flag on the specified item, i.e.void
markItemDirty(String sku, String key2)
Sets the dirty flag on the specified item, i.e.MultiKey<Object>
multiKey(Object... keys)
Constructs a new composite key object which can be used as a key in a map.Object
multiTierEntry(String entryName, String... arguments)
Creates an input parameter that lets the user enter multiple discounts/surcharges/tiers by amount.AdaptiveHistogram
newAdaptiveHistogram()
Creates a histogram that adapts to an unknown data distribution.DashboardController
newController()
Creates a new dashboard controller object that can be further customized.CreationWorkflowDefinition
newCreationWorkflow()
CreationWorkflowStepDefinition
newCreationWorkflowStep()
Object
newDatamartSlice()
Deprecated.UseDatamartContext.newDatamartSlice()
instead.Object
newDatamartSlice(String dateFieldName, Object... timePeriodsAndProductAndCustomerGroups)
Deprecated.UseDatamartContext.newDatamartSlice(String, Object...)
instead.ResultGauge
newGauge()
Creates a new gauge object that can be further customized.ResultMatrix
newMatrix()
Creates a new result matrix DTO object that can be further customized and populated with calculated data.ResultMatrix
newMatrix(String... columns)
Creates a new result matrix DTO object that can be further customized and populated with calculated data.ResultMatrix
newMatrix(Collection<String> columns)
Creates a new result matrix DTO object that can be further customized and populated with calculated data.Object
option(String entryName, Object... options)
Creates an input parameter that lets the user select a single value from the predefined options.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.Object
options(String entryName, Object... options)
Creates an input parameter that lets the user select multiple values from the predefined 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.Object
otherCustomer(String parameterName)
Triggers a custom-named customer picker input parameter.Object
otherCustomer(String parameterName, String attributeName)
Triggers a custom-named customer picker input parameter.Object
otherCustomer(String parameterName, String attributeName, boolean defaultFromParent)
Triggers a custom-named customer picker input parameter.Object
otherProduct(String parameterName)
Triggers a custom-named product picker input parameter.Object
otherProduct(String parameterName, String attributeName)
Triggers a custom-named product picker input parameter.Object
parsableInputFile(String inputName)
Creates an input parameter that lets the user pick a file.Object
parsableInputFileData(String inputName)
If a parsableInputFile has a value, this function opens the file and parses it to basic Groovy data structures.Object
parsableInputFileDataFromHandle(String fileHandle)
If a parsableInputFile has a value, this function opens the file and parses it to basic groovy datastructures.Date
parseDate(String pattern, String date)
Parses a date (entered as a String) according to the given pattern.DateTime
parseDateTime(String pattern, String datetime)
Parses a datetime (entered as a String) according to the given pattern.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.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.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.Object
pricelist(String listName)
Looks up the result price (considering a manual override) of an SKU being calculated in a price list of the given name.Object
pricelist(String listName, String attributeName)
Looks up the attribute defined byattributeName
(considering a manual override) of an SKU being calculated in a price list of the given name.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.Object
pricelist(String listName, String attributeName, String sku, String key2)
Looks up the attribute defined byattributeName
(considering a manual override) of the given SKU in a matrix price list of the given name.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.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.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.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.Object
product()
Retrieves the product object for the SKU currently being calculated.Object
product(String attributeName)
Retrieves the given attribute value from the product table for the SKU being calculated.Object
product(String attributeName, String sku)
Retrieves the given attribute value from the product table for a given SKU.Object
product(String attributeName, String sku, String filterFormulaName, Object filterFormulaParam)
Retrieves the given attribute value from the product table for a given SKU.Object
productCompetition()
Retrieves a list of all product competition records (PCOMP) for the SKU being calculated.Object
productCompetition(Filter... filters)
Retrieves a list of product competition records (PCOMP) for the SKU being calculated filtered byfilters
.Object
productExtension(String extensionName)
Retrieves a list of all product extentions records (PX) from a PX table namedextensionName
for the SKU being calculated.Object
productExtension(String extensionName, Filter... filters)
Retrieves a list of product extentions records (PX) from a PX table namedextensionName
for the SKU being calculated filtered byfilters
.Object
productGroupEntry(String... entryName)
Creates an input parameter that lets the user select a group of products and returns the selection as a Map.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.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.Object
productXRef()
Retrieves a list of all product reference records (PXREF) for the SKU being calculated.Object
productXRef(Filter... filters)
Retrieves a list of all product reference records (PXREF) for the SKU being calculated.void
putGlobal(Map<String,Object> globalVars)
Puts an entire map of variables into the global cache.Random
random()
Provides the access to the standardjava.util.Random
generator instance created for the duration of the calculation task (= not get recreated for each logic element evaluation).Object
rebateAgreementUserEntry(String parameterName, String attributeName)
Prompts the user to input parameters for a rebate agreement (RBA).void
redAlert(String msg)
Marks the current logic element with a red alert and provides the given message.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.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.void
removeManualOverride(String elementName)
Removes a user entered value that overrides the calculated result of a logic element.void
removePricegridCalculationOutput(Long pricegridId, String name)
Removes PG calculation output.Object
removePricegridInputAttribute(Long id)
Deletes a pricegrid input attribute.void
removePricelistCalculationOutput(Long pricegridId, String name)
Removes PL calculation output.Object
removePricelistInputAttribute(Long id)
Deletes a pricelist input attribute.void
removeSharedCache(String key)
Deletes a key from the shared cache.void
resetCurrentItemFields(String... fields)
Resets specified fields on currentItem object to null.void
resetSKUContextSwitch()
Resets a SKU context switch to the originally specified SKU.Map<String,String>
roles()
Lists all roles available in the application.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.void
sendEmail(String to, String subject, String message)
Sends an email.void
setAlertMessage(String msg)
Marks the current formula element with the given alert message.Object
setPricegridCalculationChart(Map<String,?> definition, Long pricegridId)
Chart definition that will be used to construct and display a Highchart in the header section.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.Object
setPricelistCalculationChart(Map<String,?> definition, Long pricegridId)
Chart definition that will be used to construct and display a Highchart in the header section.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.void
setSharedCache(String key, String value)
Stores a string value in the shared cache with the given key.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.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.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.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.Object
stringUserEntry(String entryName)
Creates an input parameter that lets the user enter a short text value.Object
stringUserEntry(String entryName, String textMask)
Creates an input parameter that lets the user enter a short text value.Object
stringUserEntry(String entryName, String textMask, String label)
Creates an input parameter that lets the user enter a short text value.void
switchSKUContext(String newSKU)
Temporarily switches the current SKU context to another SKU.Date
targetDate()
Retrieves the mandatory parameter targetDate from the current execution context.Object
textUserEntry(String entryName)
Creates an input parameter that lets the user enter a longer text value.Object
textUserEntry(String entryName, String label)
Creates an input parameter that lets the user enter a longer text value.void
throwException(String errorMessage)
Throws a calculation exception with the specified message and aborts the calculation.Object
timeUserEntry(String entryName)
Creates an input parameter that lets the user to enter a time value in format "HH:mm" (e.g.void
trace(Object result)
Generates a trace message that can be used in the logic test drive.void
trace(String functionName, Object result)
Generates a trace message that can be used in the logic test drive.void
trace(String functionName, String parameters, Object result)
Generates a trace message that can be used in the logic test drive.Long
triggerCFSCalculation(Long cfsID)
Creates a new background calculation job for the specified CFS.Long
triggerPriceGridCalculation(Long priceGridId, Map<String,Object> parameters)
Creates a new background calculation job for the specified price grid.Object
update(String typeCode, Map<String,Object> values)
Updates an object in the collection of objects of the given type.Object
updateCalculableObjectHeader(String calcObjTypeCode, String calcObjName)
Updates the header information of a CalculableObject (e.g., a price grid, a price list, etc.).Object
user()
Returns the entire master data object of the current user.Object
user(String attributeName)
Returns a value from the current user's master data.Object
userEntry(String entryName)
Triggers a numeric input element.String
uuid()
Generates a RFC4122, version 4 ID.String
uuid(int len)
Generates a random uuid of the specified length.String
uuid(int len, int radix)
Generates a random uuid of the specified length and radix.Object
vLookup(String parameterName)
Searches for a record in the price parameter table namedparameterName
where the column 'name' matches the value entered by the user and returns the value from the column 'value'.Object
vLookup(String parameterName, Object attributeNameOrKeyOrRangeValue)
Searches for a record in the price parameter table namedparameterName
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).Object
vLookup(String parameterName, String attributeName, String key)
This syntax is only relevant for MATRIX 1-key price parameter tables (MLTV).Object
vLookup(String parameterName, String attributeName, String key1, String key2)
This syntax is only relevant for MATRIX 2-key price parameter tables (MLTV2).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).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).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).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).Object
vLookup(String parameterName, String attributeName, Map keys)
This syntax can be applied to all MATRIX lookup types.Map<String,Object>
vLookup(String parameterName, List<String> attributeNames, Map keys)
This syntax can be applied to all MATRIX lookup types.Filter
walkFilter(Filter filter, Closure<?> visitBefore, Closure<?> visitAfter, boolean removeNulls)
Walks a filter and all its sub filters, visiting each filter in the tree.WrappedResult
wrap(Object result)
Wraps a result to make sure the original result object appears in the JSON response.void
yellowAlert(String msg)
Marks the current logic element with a yellow alert and provides the given message.
-
-
-
Method Detail
-
isSyntaxCheck
boolean isSyntaxCheck()
Returns true if the formula is executed in the syntax check mode. The syntax check mode is a special type of run used to determine the logic parameters in the configuration dialogs where the logics are selected (e.g. in configuration of LPGs, PLs or dashboards). The syntax check mode runs against no calculable item, so all the elements that depend on item data (e.g.product()
orcurrentItem()
as well asgetElement(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")
return api.stringUserEntry("Comment")
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 called via the UI debug/test execution mode.- Returns:
- true if executed in the debug 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. Ifapi.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 asapi.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).
- 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
- In RebateAgreement calculation there is:
- FORMULAELEMENTGROUP_RM_AGREEMENT = "agreement"
- FORMULAELEMENTGROUP_RM_AGREEMENT_READONLY = "agreementReadOnly"
- FORMULAELEMENTGROUP_RM_REBATERECORD = "rebateRecord"
- 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
- For a PA Calculation or Flush logic this can be (from PriceFxInterface):
-
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 of the previous logic element.Note: from El presidente release, there should be no need to use this function anymore, since the values from previous elements are injected as variables with the name equal to element name just with the first letter in lowercase. Works only if the element name starts with a Capital (e.g. SomeElement and not someElement).
- Parameters:
name
- The name of the logic element- Returns:
- The value or
null
if the element is not found
-
getSecondaryKey
Object getSecondaryKey()
Same asapi.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()
Retrieves the mandatory parameter targetDate from the current execution context. The target date isnew Date()
by default or overriden in:- Quotes: Quote view
- Price grids: Price grids overview window, Target date column
- Price lists: Price list creation dialog, tab Get parameters
- PA calculation dataloads: Dataload definition, Calculation tab
- Calculation flow: Calculation flow detail, Target date column
- Returns:
- The targetDate
-
calendar
Calendar calendar()
Gets ajava.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 withdate
.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 standardjava.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
-
datamartCalendar
Object datamartCalendar()
Deprecated.UseDatamartContext.calendar()
instead.- Returns:
- A
DatamartCalendar
object.
-
newDatamartSlice
@Deprecated Object newDatamartSlice()
Deprecated.UseDatamartContext.newDatamartSlice()
instead.Creates a new DatamartSlice, which allows setting filter criteria along the Time, CustomerGroup, ProductGroup or other dimensions in a Datamart.- Returns:
- The instantiated, empty,
DatamartContext.DataSlice
object
-
newDatamartSlice
Object newDatamartSlice(String dateFieldName, Object... timePeriodsAndProductAndCustomerGroups)
Deprecated.UseDatamartContext.newDatamartSlice(String, Object...)
instead.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 fieldtimePeriodsAndProductAndCustomerGroups
- 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)
Deprecated.This method is deprecated and exists only for backward compatibility for older in-production formulas. Use the Groovy query API instead (seeDatamartContext
). 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.UseDatamartContext.executeQuery(DatamartContext.Query)
,net.pricefx.formulaengine.DatamartContext#executeSqlQuery(String, DatamartContext.Query...)
orDatamartContext.streamQuery(DatamartContext.Query)
This method is deprecated and only exists for backward compatibility for older in-production formulas. Use the Groovy query API instead (seeDatamartContext
). 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:- getting the PA Datamart using
DatamartContext.getDatamart(String)
to be further queried - getting the PA Data Source using
DatamartContext.getDataSource(String)
to be further queried - getting the PA calendar using
DatamartContext.calendar()
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
- getting the PA Datamart using
-
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, aDatamartRowSet
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, aDatamartRowSet
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)
-
switchSKUContext
void switchSKUContext(String newSKU)
Temporarily switches the current SKU context to another SKU. This can be used to call functions that rely on a SKU context and do not allow to specify an alternate SKU with a different SKU.product()
productCompetition()
productExtension(String)
productXRef()
bom()
bomList()
pricelist(String)
getPricelistItem(String)
resetSKUContextSwitch()
or automatically at the beginning of every element.Example:
def masterSku = api.productXRef() def costs if (masterSku) { api.switchSKUContext(masterSku[0].targetSku) // take the cost from the masterSku item costs = api.productExtension("Cost") api.resetSKUContextSwitch() } else { // take the cost from the item being calculated costs = api.productExtension("Cost") } if (costs) { .... }
- Parameters:
newSKU
- The new SKU to switch to.- See Also:
resetSKUContextSwitch()
,product(String, String)
-
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. The 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
Object product(String attributeName)
Retrieves the given attribute value from the product table for the SKU being calculated. The product object is cached and the next call reads the value from the cached record.Example:
def label = api.product("label") def productGroup = api.product("attribute1") // Product Group def manufacturer = api.product("attribute4") // Manufacturer
- Parameters:
attributeName
- The attribute value to be returned- Returns:
- The value of the attribute
- See Also:
currentItem(String)
-
product
Object product(String attributeName, String sku)
Retrieves the given attribute value from the product table for a given SKU.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 attribute whose value should be returnedsku
- The product- Returns:
- The value of the attribute (or
null
if product not found)
-
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 returnedsku
- The productfilterFormulaName
- Unique name of a formula that will be triggered when the Product picker opensfilterFormulaParam
- Additional data for filterFormula- Returns:
- The value of the attribute (or
null
if product not found)
-
otherProduct
Object otherProduct(String parameterName, String attributeName)
Triggers a custom-named product picker input parameter.- Parameters:
parameterName
- The name of the parameterattributeName
- The attribute whose value should be returned (null
for the entire object)- 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 all product extentions records (PX) from a PX table namedextensionName
for the SKU being calculated. Consider use ofgetBatchInfo()
for the performance reasons.Example:
def promotions = api.productExtension("Promotion") if (promotions) { def promotion = promotions.getAt(0) ... }
- Parameters:
extensionName
- The name of the extension- Returns:
- List of PX records (represented as a Map)
- See Also:
getBatchInfo()
-
productExtension
Object productExtension(String extensionName, Filter... filters)
Retrieves a list of product extentions records (PX) from a PX table namedextensionName
for the SKU being calculated filtered byfilters
. Consider use ofgetBatchInfo()
for the performance reasons.Example:
def filter = [ Filter.greaterOrEqual("attribute1", targetDate), // Valid from Filter.lessOrEqual("attribute2", targetDate) // Valid to ] def promotions = api.productExtension("Promotion", *filter) if (promotions) { def promotion = promotions.getAt(0) ... }
- Parameters:
extensionName
- The name of the extensionfilters
- One or moreFilter
objects that narrow down the search- Returns:
- List of matching PX records (represented as a Map)
- See Also:
getBatchInfo()
-
productCompetition
Object productCompetition()
Retrieves a list of all product competition records (PCOMP) for the SKU being calculated. Consider usingproductExtension(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 records (PCOMP) for the SKU being calculated filtered byfilters
. Consider usingproductExtension(String)
instead since that gives you a better flexibility.- Parameters:
filters
- One or moreFilter
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 ofgetBatchInfo()
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 moreFilter
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 customer object for the SKU currently being calculated. The customer object is cached and the next call reads the value from cached record.- Parameters:
attributeName
- The attribute value to be returned- 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 isnull
and defaultFromParent istrue
, it retrieves (and returns) the value from the customer's parent regardless if that value isnull
as well or not. If there is no parent customer set,null
will be returned.- Parameters:
attributeName
- The attribute value to be returneddefaultFromParent
- Determines whether to look up the value from the parent customer (if any) in case it isnull
in the customer- Returns:
- The value of the attribute
-
customer
Object customer(String attributeName, String customerId)
Retrieves the given attribute value from the customer table for the SKU being calculated. The customer object is cached and the next call reads the value from the cached record.- Parameters:
attributeName
- The attribute value to be returnedcustomerId
- The customerId value for the customer search- 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 isnull
and defaultFromParent istrue
, it retrieves (and returns) the value from the customer's parent regardless if that value isnull
as well or not. If there is no parent customer set,null
will be returned.- Parameters:
attributeName
- The attribute value to be returnedcustomerId
- The customerId value for the customer searchdefaultFromParent
- Determines whether to look up the value from the parent customer (if any) in case it isnull
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 isnull
and defaultFromParent istrue
, retrieves (and returns) the value from the customer's parent regardless if that value isnull
as well or not. If there is no parent customer set,null
will be returned)- Parameters:
attributeName
- The attribute value to be returnedcustomerId
- The customerId value for the customer searchdefaultFromParent
- Determines whether to look up the value from the parent customer (if any) in case it isnull
in the customerfilterFormulaName
- Unique name of a formula that will be triggered when the Customer picker opensfilterFormulaParam
- 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 parameterattributeName
- 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 parameterattributeName
- 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 isnull
in the customer- Returns:
- The attribute value
-
customerExtension
Object customerExtension(String extensionName, Filter... filters)
Retrieves a list of all customer extentions records (CX) from a CX table namedextensionName
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 extensionfilters
- None, one or moreFilter
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 itemresultNamesOrLabels
- 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 formula execution warning log. The warnings are displayed:- in a column in the element results list (Quotes, Rebate agreements, Contract agreements)
- in a column in the grid list items (Pricelists, Pricegrids, Datamarts, Policy records)
Example:
def cost = if (!cost) { api.addWarning("Missing cost") }
- 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 namedparameterName
where the column 'name' matches the value entered by the user and returns the value from the column 'value'.- Parameters:
parameterName
- The name of the price parameter table- Returns:
- The user selected value, 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 namedparameterName
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("attribute2") def shippingCost = api.vLookup("ShippingCosts", productGroup)
- Parameters:
parameterName
- The name of the price parameter tableattributeNameOrKeyOrRangeValue
- 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 namedparameterName
where the column 'key1' matches thekey1
parameter and returns the value of the columnattributeName
. 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 tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskey
- 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 namedparameterName
where the columns 'key1'-'key2' match thekey1
-key2
parameters and returns the value from the columnattributeName
. 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 tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskey1
- The key1 of the parameter tablekey2
- 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 namedparameterName
where the columns 'key1'-'key3' match thekey1
-key3
parameters and returns the value from the columnattributeName
. 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 tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskey1
- The key1 of the parameter tablekey2
- The key2 of the parameter tablekey3
- 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 namedparameterName
where the columns 'key1'-'key4' match thekey1
-key4
parameters and returns the value from the columnattributeName
. 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 tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskey1
- The key1 of the parameter tablekey2
- The key2 of the parameter tablekey3
- The key3 of the parameter tablekey4
- 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 namedparameterName
where the columns 'key1'-'key5' match thekey1
-key5
parameters and returns the value from the columnattributeName
. 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 tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskey1
- The key1 of the parameter tablekey2
- The key2 of the parameter tablekey3
- The key3 of the parameter tablekey4
- The key4 of the parameter tablekey5
- 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 namedparameterName
where the columns 'key1'-'key6' match thekey1
-key6
parameters and returns the value from the columnattributeName
. 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 tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskey1
- The key1 of the parameter tablekey2
- The key2 of the parameter tablekey3
- The key3 of the parameter tablekey4
- The key4 of the parameter tablekey5
- The key5 of the parameter tablekey6
- 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.- Parameters:
parameterName
- The name of the price parameter tableattributeName
- The name of the attribute to retrieve, or a comma separated list of attributeskeys
- 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 tableattributeNames
- The names of the attribute to retrievekeys
- 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
-
userEntry
Object userEntry(String entryName)
Triggers a numeric input element.- When the user entered number is a whole number (integer), the value returned is java.lang.Integer.
- When the user entered number is a decimal number, the value returned is java.math.BigDecimal.
- If you always need the result as a BigDecimal, you can cast it, e.g. api.decimalUserEntry("number") as BigDecimal.
- Parameters:
entryName
- The name of the user entry parameter- Returns:
- The user entered value
- See Also:
input(String)
,stringUserEntry(String)
,(String...)
,decimalUserEntry(String)
,dateUserEntry(String)
,dateRangeUserEntry(String)
,dateTimeUserEntry(String)
,booleanUserEntry(String)
,option(String, Object...)
,options(String, Object...)
,filterBuilderUserEntry(String, String)
,datamartFilterBuilderUserEntry(String, String, Object...)
,otherProduct(String)
,otherCustomer(String)
,productGroupEntry(String...)
,customerGroupEntry(String...)
,rebateAgreementUserEntry(String, String)
,anyUser(String)
,inputMatrix(String, String...)
-
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)
Creates an input parameter that lets the user enter an integer value. Rendered as a numeric field.- Parameters:
entryName
- The name of the user entry parameter- Returns:
- Integer value entered by the user as a BigDecimal
- See Also:
decimalUserEntry(String)
-
stringUserEntry
Object stringUserEntry(String entryName)
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- 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 parametertextMask
- 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 parametertextMask
- Optional text mask that is displayed in the UIlabel
- 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 parameterlabel
- 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
-
dateUserEntry
Object dateUserEntry(String entryName)
Creates an input parameter that lets the user enter a date value. Rendered as a date picker field.- Parameters:
entryName
- The name of the user entry parameter- Returns:
- String value entered by the user in the format yyyy-MM-dd
- See Also:
parseDate(String, String)
,timeUserEntry(String)
,dateTimeUserEntry(String)
,dateRangeUserEntry(String)
-
dateRangeUserEntry
Object dateRangeUserEntry(String entryName)
Creates an input parameter that lets the user enter a date range (start and end date). Rendered as two date picker fields. UNITY UI ONLY!- Parameters:
entryName
- The name of the user entry parameter- Returns:
- String array or list with values entered by the user in the format yyyy-MM-dd
- See Also:
parseDate(String, String)
,timeUserEntry(String)
,dateTimeUserEntry(String)
,dateUserEntry(String)
-
timeUserEntry
Object timeUserEntry(String entryName)
Creates an input parameter that lets the user to enter a time value in format "HH:mm" (e.g. "23:59"). Rendered as a time picker field.- Parameters:
entryName
- The name of the user entry parameter- Returns:
- String value entered by the user in the format HH:mm
- See Also:
parseDate(String, String)
,dateUserEntry(String)
,dateTimeUserEntry(String)
,dateRangeUserEntry(String)
-
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" ]
-
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 parameterfilterFormulaName
- A unique name of a formula that will be triggered when the customer picker opensfilterFormulaParam
- 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...)
-
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 parameterfilterFormulaName
- A unique name of a formula that will be triggered when the customer picker opensfilterFormulaParam
- 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 parameterarguments
- 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)
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.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 parameteroptions
- An arbitrary number of options that should be displayed in the drop down list- Returns:
- The user entered value
- 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 parameteroptions
- An arbitrary number of options that should be displayed in the drop down listlabels
- 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 parameteroptions
- 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 parameteroptions
- An arbitrary number of options that should be displayed in the drop down listlabels
- A map [value : label] of labels that should be shown in the UI. If null or empty will behave same asoption(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 bytypeCode
parameter.It is rendered as a filter builder widget allowing to construct a filter (e.g. to define filter for Products, set the
typeCode
toP
).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 parametertypeCode
- 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 thedatamartQuery(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 parametersource
- The name of the source for which the filter is set. The resolution of the source is as follows:- any Datamart - by typedId, sourceName, uniqueName or label (uniqueName and label for backwards compatibility)
- 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 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 chosen.- Parameters:
listName
- The name of the price list- Returns:
- The
resultPrice
of the price list record for the SKU
-
pricelist
Object pricelist(String listName, String attributeName)
Looks up the attribute defined byattributeName
(considering a manual override) 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 multiple price lists are found, the one with the targetDate closer to the calculation targetDate is chosen.- Parameters:
listName
- The name of the price listattributeName
- 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 listattributeName
- The name of the attribute to retrievesku
- 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 byattributeName
(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 listattributeName
- The name of the attribute to retrievesku
- The SKU to usekey2
- 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 listsku
- 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 listsku
- The SKU to usekey2
- 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 listsku
- The SKU to usekey2
- The key2 to usetargetDate
- 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 thepricelistItem(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 namecategoryName
- 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 namecategoryName
- The category name to filter onmaterialName
- 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 render any input widget.- Parameters:
inputName
- The parameter name- Returns:
- The parameter value
- 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 parametercolumnNames
- 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 parameterparamConfig
- 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.UseFilter.equal(String, Object)
insteadCreates 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 onvalue
- 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
-
filter
Object filter(String property, Object opString, Object value)
Deprecated.Use theFilter
functions insteadCreates a filter object that can be used in other API functions.Note: This method is sort of dynamic. Dynamic in a sense that if the
opString
does not actually represent a valid operator (e.g. "="), the passed value will then be treated as the lower bound and thevalue
as the upper bound. In other words, the resulting filter will look like this:Filter.and(Filter.greaterOrEqual(property, opString), Filter.lessThan(property, value))
. If either parameter isnull
, its part is skipped.Example:
datamartQuery.where(api.filter("PricingDate", ">", targetDate.minus(365).format("yyyy-MM-dd")))
- Parameters:
property
- The name of the property to filter onopString
- One out of : "=", "<", "<=", ">", ">=", "<>", "~". If different, it gets treated as the lower bound value. Please see the remark.value
- The specified value (or an upper bound)- Returns:
- A filter object
- See Also:
Filter.equal(String, Object)
,Filter.lessThan(String, Object)
,Filter.lessOrEqual(String, Object)
,Filter.greaterOrEqual(String, Object)
,Filter.greaterThan(String, Object)
,Filter.notEqual(String, Object)
,Filter.like(String, String)
,Filter.and(Filter...)
,Filter.or(Filter...)
,Filter.in(String, Object...)
,Filter.notIn(String, 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 nameloginUserName
- 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 in the logic test drive. During the regular logic execution trace messages are ignored. The parameters specify the output of the trace.- Parameters:
functionName
- A function name (free text of your choice)parameters
- Parameters to traceresult
- The result of the trace
-
trace
void trace(String functionName, Object result)
Generates a trace message that can be used in the logic test drive. During the regular logic execution trace messages are ignored. The parameters specify the output of the trace.- Parameters:
functionName
- A function name (free text of your choice)result
- The result of the trace
-
trace
void trace(Object result)
Generates a trace message that can be used in the logic test drive. During the regular logic execution trace messages are ignored.- Parameters:
result
- The value to trace
-
log
void log(String msg, Object arg1)
This function is meant to be used by the Pricefx internally only. You should uselogInfo(String, Object)
orlogWarn(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 printarg1
- 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 uselogInfo(Object)
orlogWarn(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 printarg1
- 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 printarg1
- 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 step) input parameter in the form of aContextParameter
object. This can then be further modified as required.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 named parameter to retrieve- Returns:
- The parameter 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 forkey2
- 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 forkey2
- 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 retrievepath
- 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 retrieveelementName
- 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 (e.g., price list item or price grid item or quote item).Example:
def currentItem = api.currentItem() def currentSku = currentItem != null ? currentItem.attribute20 : api.product("attribute20")
- Returns:
- The item object as a Map
-
currentItemByElementName
Object currentItemByElementName(String elementName)
In case of a list processing operation, this method gets the currently worked on record's property by elementName.- Parameters:
elementName
- The element name- Returns:
- The item's property value
-
currentItem
Object currentItem(String attributeName)
Same ascurrentItem()
but returns only the specified attribute.Example:
def activePrice = api.currentItem("activePrice")
- Parameters:
attributeName
- The attribute to retrieve- Returns:
- The value of the attribute
-
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
-
getMaxFindResultsLimit
int getMaxFindResultsLimit()
Returns the maximum number of records thatfind(String, int, int, String, Filter...)
and its variations can return in one call. The value is set informulaEngine.script.findMaxResults
system parameter. The default value is 2000 records.- Returns:
- the maximum number of records
- See Also:
find(String, int, int, String, Filter...)
-
find
List<Object> find(String typeCode, Filter... filters)
Deprecated.usefind(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 usefind(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.usefind(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 usefind(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.usefind(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 usefind(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 setsortBy
- String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort orderfilters
- 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 setmaxRows
- The maximum number of rows to retrieve. Value can be up togetMaxFindResultsLimit()
. If set to 0 it will default to 200sortBy
- String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort orderfilters
- 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 setmaxRows
- The maximum number of rows to retrieve. Value can be up togetMaxFindResultsLimit()
. If set to 0 it will default to 200sortBy
- String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort orderfields
- A list of fields to returned in the result. If you really need all fields, you can set this parametr to nullfilters
- 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 setmaxRows
- The maximum number of rows to retrieve. Value can be up togetMaxFindResultsLimit()
. If set to 0 it will default to 200sortBy
- String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort orderfields
- A list of fields to returned in the result. If you really need all fields, you can set this parametr to nulldistinctValuesOnly
- 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 setmaxRows
- The maximum number of rows to retrieve. Value can be up togetMaxFindResultsLimit()
. If set to 0 it will default to 200sortBy
- String of fields/attributes, separated by comma, based on which the resultset should be sorted. Any field can be prefixed with '-' for descending sort orderfields
- 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 usestream(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 orderfilters
- 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.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 orderfields
- 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.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 orderfields
- 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.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 orderfields
- 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 MAXdistinctValuesOnly
- 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...)
-
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.- 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
-
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 sortfilters
- The filters to apply to the RebateRecord search- Throws:
InterruptedException
- if interrupted while waiting
-
emitPersistedObject
boolean emitPersistedObject(String typedId) throws InterruptedException
Finds the PersistedObject with the given typedId and emits it if it exists. The assumption is that there is a receiving consumer, as inemitRebateRecords(java.lang.String, java.lang.String, com.googlecode.genericdao.search.Filter...)
.- Parameters:
typedId
- The typedId of the PersistedObject to emit- Returns:
- false if failed
- Throws:
InterruptedException
- if interrupted while waiting
-
emitPersistedObject
boolean emitPersistedObject(String typeCode, Long id) throws InterruptedException
Finds the PersistedObject for the given type and ID and emits it if it exists. The assumption is that there is a receiving consumer, as inemitRebateRecords(java.lang.String, java.lang.String, com.googlecode.genericdao.search.Filter...)
.- Parameters:
typeCode
- The typeCode of the PersistedObject to emitid
- The ID of the PersistedObject to emit- Returns:
- false if failed
- Throws:
InterruptedException
- if interrupted while waiting
-
count
int count(String typeCode, Filter... filters)
Returns the number of records that a correspondingfind(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 ofFilter
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. It does apply target date and simulation set matching. There is no caching of the values, so the caching should be considered.- 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 all values of a named price parameter table (optionally filtered). 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").collectEntries { [(it.name): it.value] } } return api.global.salesOrgs
- Parameters:
tableName
- The name of the price parameter tablefilters
- Optional extraFilter
- Returns:
- The price parameter table values or
null
-
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 IDworkflowStatuses
- 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 IDworkflowStatuses
- 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 uselistName
- Price list name. Ifnull
, 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 usesimulationName
- Simulation name. Ifnull
, 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 usepriceGridName
- Price grid name. Ifnull
, 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 CFScfsName
- CFS name. Ifnull
, 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 uselistName
- Price list name. Ifnull
, 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 groupstartRow
- 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 run at all, so the condition would not be evaluated).
- Parameters:
elementName
- The formula/result element that is overridden
-
abortCalculation
void abortCalculation()
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 withisSyntaxCheck()
after the parameters are gathered.Example:
if (api.isSyntaxCheck()) { api.abortCalculation() }
-
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 withisSyntaxCheck()
after the parameters are gathered.- Parameters:
keepOld
- Should the old outputs be retained? Only applicable for quote and contract calculation!
-
throwException
void throwException(String errorMessage) throws XExpression
Throws a calculation exception with the specified message and aborts the calculation.- 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 alsogetIterationNumber()
,markItemClean()
. The maximum number of dirty passes is defined by the server configuration constantmaxDirtyCalculations
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 constantmaxDirtyCalculations
defined for the whole instance. The default is 1 dirty pass. See alsogetIterationNumber()
,markItemClean()
.- Parameters:
sku
- The item to have the dirty flag setkey2
- 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 constantmaxDirtyCalculations
defined for the whole instance. The default is 1 dirty pass. See alsogetIterationNumber()
,markItemClean()
.- See Also:
markItemClean()
-
markItemClean
void markItemClean()
Removes the dirty flag from the current item set previously bymarkItemDirty()
.- See Also:
markItemDirty()
-
markItemClean
void markItemClean(String sku, String key2)
Removes the dirty flag from the specified matrix item set previously bymarkItemDirty(String, String)
.- Parameters:
sku
- The item from which to remove the dirty flagkey2
- key2 field- See Also:
markItemDirty(String, String)
-
markItemClean
void markItemClean(String sku)
Removes the dirty flag from the specified item set previously bymarkItemDirty(String)
.- Parameters:
sku
- The item from which to remove the dirty flag- See Also:
markItemDirty(String)
-
isSecondPass
boolean isSecondPass()
Deprecated.UsegetIterationNumber()
> 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 constantmaxDirtyCalculations
defined for the whole instance. The default is 1 dirty pass.- Returns:
- The iteration number
-
formatString
String formatString(String locale, String format, Object... args)
Formats a string likeString.format(java.lang.String, java.lang.Object...)
.- Parameters:
locale
- The locale (as a String)format
- The format stringargs
- The arguments to pass on- Returns:
- The formatted string
-
formatNumber
String formatNumber(String pattern, Object n)
Formats a number as a String. The same semantics asNumberFormat
andDecimalFormat.applyPattern(java.lang.String)
apply.- Parameters:
pattern
- The pattern stringn
- The number to format- Returns:
- The formatted number as a String
-
formatNumber
String formatNumber(String locale, String pattern, Object n)
Formats a number as a String. The same semantics asNumberFormat
andDecimalFormat.applyPattern(java.lang.String)
apply.- Parameters:
pattern
- The pattern stringn
- The number to formatlocale
- The locale to use for formatting- Returns:
- The formatted number as a String
-
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 mapomitNull
- 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, 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'). In a quote 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, 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, 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. 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(Object definition)
Deprecated.CallsbuildFlexChart(null, definition)
See the full documentation inbuildFlexChart(Object)
.- Parameters:
definition
- the definition of theFlexChart
- Returns:
- ResultFlexChart object
- See Also:
buildHighchart(Map)
,buildFlexChart(String, Object)
-
buildFlexChart
ResultFlexChart buildFlexChart(String baseTemplateToUse, Object definition)
Deprecated.Creates aFlexChart
from the passeddefinition
by merging it withoptions
defined within thebaseTemplateToUse
template.Although it may change in future releases, for now, a
FlexChart
is nothing else than aHighcharts
chart. Therefore, the passeddefinition
(also applies to thebaseTemplateToUse
template) must denoteHighcharts options
- please consultHighcharts
documentation for more details, and note that FlexCharts must comply to the outdated Highcharts release 4.Since
Highcharts options
are normally specified by aJavaScript object literal
, the passeddefinition
must be either aJSON
string representing suchobject literal
, or anyobject
which can be mapped to suchJSON
representation. Therefore, typically thedefiniton
will be passed as amap 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)
Highcharts options
are supported. Moreover, usage of some options is prohibited deliberately. These are currentlyglobal
,events
and everyJavaScript 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 passeddefinition
; ifnull
, the predefined Default template is useddefinition
- The definition of theFlexChart
; currently, this will typically be a string or map of maps containingHighcharts 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)
-
buildHighchart
ResultHighchart buildHighchart(Map<String,?> definition)
Creates aResultHighchart
from the passeddefinition
.
As opposed toFlexChart
, the definition is passed straight to theHighcharts
library, currently release 7.1. There is no validation, no templates merging, and JavaScript functions are not supported.- Parameters:
definition
- The definition of theHighchart
as a map of maps and arrays- Returns:
- ResultHighchart object
- See Also:
- https://www.highcharts.com/docs,
https://api.highcharts.com/highcharts,
buildFlexChart(Object)
-
buildHighmap
ResultHighmap buildHighmap(Map<String,?> definition)
Creates aResultHighmap
from the passeddefinition
.
As opposed toFlexChart
, the definition is passed straight to theHighmaps
library, currently release 7.1. There is no validation, no templates merging, and JavaScript functions are not supported.HighChart
provide better performance thanFlexChart
since- Parameters:
definition
- The definition of theHighmap
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 inrunSummaryQuery(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 inrunSummaryQuery(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 inrunSummaryQuery(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 inrunSummaryQuery(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, HIDDENname
- 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, HIDDENname
- The name of the parametertargetDate
- 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)
orConfiguratorEntryArray#getEntries()
-
configurator
Object configurator(String configuratorName, String formulaName)
- Parameters:
configuratorName
- The name of the configurator, similar to other options' namesformulaName
- 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' namesformulaName
- The name of the configurator formula which is used to drive the input selectionsresultName
- 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' namesformulaName
- The name of the configurator formula which is used to drive the input selectionswidth
- 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' namesformulaName
- The name of the configurator formula which is used to drive the input selections- Returns:
- The result of the configurator
-
parseDate
Date parseDate(String pattern, String date)
Parses a date (entered as a String) according to the given pattern.Hint: For parsing datetimes (i.e. dates also including information about the time of the day), use the
parseDateTime(String, String)
method instead.Example:
def date = api.parseDate("yyyy-MM-dd", "2019-01-23")
- Parameters:
pattern
- The pattern for parsing (see DateTimeFormat for pattern format specification)date
- The date as a String in the format specified by thepattern
- Returns:
- The date
- See Also:
parseDateTime(String, String)
,parseDateTime(String, String, int, int)
-
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 theparseDateTime(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 thepattern
- 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 thepattern
tzHoursOffset
- The offset in hours from UTC, from -23 to +23tzMinutesOffset
- 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 attributelistTypedIds
- 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.- Parameters:
url
- The full URL to the HTTPS or HTTP endpointbody
- 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 Price fx server, either local one or an external one. 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 partitionrelativeUrl
- The relative URL to the Pricefx server command. First slash excluded.body
- The body of the requestresponseBodyAsAString
- 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.- Parameters:
url
- The full URL to the HTTPS or HTTP endpointbody
- The body of the requestmethodType
-"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"
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
- basicAuthenticationUserName
- 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
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 ])
api.addOrUpdate("PGI", [ "priceGridName" : "LifeCycleMonitor", "sku" : currentItem.sku, "label" : currentItem.label ])
def large = [ "lookupTableId" : pp.id, "lookupTableName" : pp.uniqueName, "name" : "L", "attribute1" : percentileHigh, "attribute2" : "999999999" ] api.addOrUpdate("MLTV", large)
- 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 tosubject
- The email subjectmessage
- The email body
-
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 eventcustomEventType
- 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 eventcustomEventType
- 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 eventcustomEventType
- 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 updatecalcObjName
- The (numeric) ID of the object to update- Returns:
- The calculable Object Header
-
attributedResult
AttributedResult attributedResult(Object result)
Creates anAttributedResult
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 innewMatrix()
.- 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 innewMatrix()
.- 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 objectvisitBefore
- The before closurevisitAfter
- The after closureremoveNulls
- 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 UIdataLoadType
- 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 charactersradix
- 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
- Ifpo
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
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
- addition
-
setSharedCache
void setSharedCache(String key, String value)
Stores a string value in the shared cache with the given key. Note the "global" nature of the key.- Parameters:
key
- The cache keyvalue
- The value to store- See Also:
getSharedCache(String)
,removeSharedCache(String)
-
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)
-
removeSharedCache
void removeSharedCache(String key)
Deletes a key from the shared cache.- Parameters:
key
- The cache key- See Also:
setSharedCache(String, String)
-
base64Encode
String base64Encode(String string)
Provides a standard Base64 encoding of a string.Example:
api.base64Encode("Price f(x)") // "UHJpY2UgZih4KQ=="
- Parameters:
string
- The plain text to be encoded- Returns:
- The base64 encoded string
- See Also:
base64Decode(String)
, https://en.wikipedia.org/wiki/Base64
-
base64Decode
String base64Decode(String base64String)
Decodes a base64 encoded string.Example:
api.base64Decode("UHJpY2UgZih4KQ==") // "Price f(x)"
- Parameters:
base64String
- The base64 encoded text- Returns:
- The plain text string
- See Also:
base64Encode(String)
, https://en.wikipedia.org/wiki/Base64
-
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 supportedskus
- A set of SKU strings that should be searched for- Returns:
- A list of reference records
-
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.euExample:
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 calculateparameters
- 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. attribute12elementName
- Name of the column, e.g. colourlabel
- Label of the column, e.g. ColourpriceGridId
- pricegrid id which can usually be obtained by usingapi.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. attribute12elementName
- Name of the column, e.g. colourlabel
- Label of the column, e.g. ColourpriceGridId
- pricegrid id which can usually be obtained by usingapi.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 usingapi.currentItem("id")
name
- name of the calculation output, e.g. saleslabel
- label of the calculation output, e.g. Global Salesvalue
- calculated value, e.g. €2.3Mmessage
- 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 usingapi.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 mappricegridId
- pricegrid id which can usually be obtained by usingapi.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 usingapi.currentItem("id")
name
- name of the calculation output, e.g. saleslabel
- label of the calculation output, e.g. Global Salesvalue
- calculated value, e.g. €2.3Mmessage
- 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 usingapi.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 mappricelistId
- pricelist id which can usually be obtained by usingapi.currentItem("id")
- Returns:
- saved chart definition
-
-