sdk promotion calculation engine - sap help portal · pdf filesdk promotion calculation engine...

74
Promotion Calculation Engine Document Version: 1.0 – 2017-06-08 CUSTOMER SDK Promotion Calculation Engine SAP Customer Activity Repository 3.0 FP1

Upload: ngotram

Post on 31-Mar-2018

225 views

Category:

Documents


3 download

TRANSCRIPT

Promotion Calculation Engine Document Version: 1.0 – 2017-06-08

CUSTOMER

SDK Promotion Calculation Engine SAP Customer Activity Repository 3.0 FP1

SDK Promotion Calculation Engine2 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Typographic Conventions

Typographic Conventions

Type Style Description

Example Words or characters quoted from the screen. These include field names, screen titles, pushbuttonslabels, menu names, menu paths, and menu options.

Textual cross-references to other documents.

Example Emphasized words or expressions.

EXAMPLE Technical names of system objects. These include report names, program names, transaction codes,table names, and key concepts of a programming language when they are surrounded by body text,for example, SELECT and INCLUDE.

Example Output on the screen. This includes file and directory names and their paths, messages, names ofvariables and parameters, source text, and names of installation, upgrade and database tools.

Example Exact user entry. These are words or characters that you enter in the system exactly as they appear inthe documentation.

<Example> Variable user entry. Angle brackets indicate that you replace these words and characters withappropriate entries to make entries in the system.

EXAMPLE Keys on the keyboard, for example, F2 or ENTER .

SDK Promotion Calculation EngineDocument History © 2016 SAP SE or an SAP affiliate company. All rights reserved. 3

Document History

Version Date Change

1.0 2017-06-08 Initial version

SDK Promotion Calculation Engine4 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Content

1 Preface .......................................................................................................................... 6

2 What is new in this release ............................................................................................. 7

3 Getting Started .............................................................................................................. 8

4 PCE Basics .................................................................................................................... 104.1 Request structure ........................................................................................................ 104.2 Response structure ...................................................................................................... 114.3 Calculation modes ........................................................................................................ 12

4.3.1 Basket mode .................................................................................................. 134.3.2 LineItem mode ............................................................................................... 13

5 How the PCE works ...................................................................................................... 145.1 Request processing ...................................................................................................... 155.2 Eligibility loading .......................................................................................................... 165.3 Promotion calculation .................................................................................................. 165.4 Update transaction ...................................................................................................... 175.5 Create response ........................................................................................................... 175.6 Bucket calculation ........................................................................................................ 18

6 The data access layer (DAL) .......................................................................................... 19

7 How to extend the PCE................................................................................................. 217.1 PCE Context ................................................................................................................. 217.2 Object factories and how to extend them .................................................................... 227.3 Transaction analyzer .................................................................................................... 23

7.3.1 Spring bean configuration .............................................................................. 247.3.2 Add a new transaction analyzer and register it ............................................... 24

7.4 Eligibility loader ........................................................................................................... 257.4.1 Spring bean configuration .............................................................................. 257.4.2 Add a new eligibility loader and register it or extend a existing ....................... 26

7.5 Calculation Rules (Discount operations) ....................................................................... 277.5.1 Spring bean configuration .............................................................................. 28

7.6 Add and register a new calculation rule ........................................................................ 307.7 Price Modification ........................................................................................................ 31

7.7.1 Spring bean configuration .............................................................................. 327.7.2 Add and register a new price modification...................................................... 32

7.8 Transaction update handler ......................................................................................... 337.8.1 Spring configuration ....................................................................................... 34

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 5

7.8.2 Exchange TransactionUpdateHandler ............................................................. 347.9 List of all beans in pricing engine impl .......................................................................... 36

8 Business Error Codes .................................................................................................... 408.1 Error message format .................................................................................................. 418.2 Business Error Codes .................................................................................................... 41

9 PCE API interfaces ........................................................................................................ 44

10 PCE models .................................................................................................................. 4610.1 Promotion Master Data................................................................................................ 4610.2 Transaction .................................................................................................................. 48

11 Configuration ............................................................................................................... 5211.1 PromotionServiceConfig ............................................................................................... 52

11.1.1 Configuration as input parameter ................................................................... 5211.1.2 Configuration by configuration file(s) available at service site ......................... 52

12 Libraries ....................................................................................................................... 60

13 Performance Logging ................................................................................................... 6213.1 Overview ..................................................................................................................... 6213.2 Usage ........................................................................................................................... 62

13.2.1 Measurement Points ...................................................................................... 6413.2.2 Analysis of Performance logs .......................................................................... 68

13.3 Development ............................................................................................................... 71

14 Glossary ....................................................................................................................... 73

SDK Promotion Calculation Engine6 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

1 Preface

In an integrated Omnichannel concept, the Promotion Calculation Engine (PCE) ensures homogeneouspricing, the consistent application of promotions, and loyalty activities as well as the accurate calculation ofrefunds across all channels.

The highly configurable solution is designed to handle a large number of price calculations simultaneouslyacross multiple channels and in real time.

The subsequent chapters provide you with an in-depth look into how the PCE operates. You will get to knowthe algorithm and the technology behind the PCE and learn how to extend it according to your needs.

Notethatthisdocumentationoccasionallyusestheterm"PricingEngine".ThistermdenotesthecorecomponentsofthePromotionCalculationEngine.AsthePricingEnginecomprisesapartofthePCE,itmustnotbeconfusedwiththePCEitself.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 7

2 What is new in this release

The following section describes the main features and differences between PCE versions 1 and 2.

PCE 1.0

· Hard coupled with the GK/Retail OmniPOS System, which means a lot of libraries for the standaloneversion increasing the size and making maintenance dependent upon the OmniPOS release cycle.

PCE 2.x

· Standalone version, no more dependencies with the OmniPOS system.

· Can work as library (integrated via Maven and called with exposed services) and as a web service(starting an integrated web app).

· The following requirements are fulfilled:

o Calculation modes line item, basket,

o API major version 2,

o multi-language support,

o calculation based on BigDecimal,

o manual trigger and manual rules,

o fully priced items,

o item OR,

o a number of bug fixes, code improvements and library updates.

SDK Promotion Calculation Engine8 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

3 Getting Started

The Promotion Calculation Engine (PCE) is a software artifact designed to calculate promotions over items(line items) presented in a transaction. The PCE calculates promotions related to the line items and alsoprocesses coupons and assigned customer groups.

Technically, the PCE gets requests via a client exposed interface API. These requests are expressed in Javaobjects which store the transaction and line items that belong to a sales order. The objects contain allnecessary information regarding the product. An incoming request is analyzed and mapped to internal PCEmodels. The PCE extracts information from the transaction. Afterwards, if applicable, monetary discountsare calculated, for example, promotion rebates, discounts such as “buy 3 pay 2”, manual rebates, etc.

The result of the PCE calculation is mapped back to an exposed Java object and returned to the requestingprocess, for example, another Java application.

The following figure demonstrates the PCE process in a larger context:

In order to process promotions and to apply them to line items, the PCE works like a rule engine with so-called “promotion items". A promotion item contains condition rules (for example, "promotion only appliesif you buy for more than 100 €") and so-called eligibilities. An eligibility can be thought of as a trigger for apromotion.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 9

Promotions may be applied on a single transaction or line items. In this case, the promotions must behandled with a promotion collision handler algorithm.

The API communication is for SAP stateless and without any GUI. The responsibility for storing informationreceived from the PCE is delegated to the called process.

The transmitted content is based on the ARTS Pricing Service Interface schema.

SDK Promotion Calculation Engine10 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

4 PCE Basics

4.1 Request structure

The PCE is called via the Pricing Service API. The requester has to send a PriceCalculate representation (seecom.sap.ppengine.client.dto.PriceCalculate). The PriceCalculate object contains the required information.

The representation of a PriceCalculate in XML can be seen in the following sample:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><PriceCalculate xmlns="http://www.sap.com/IXRetail/namespace/" InternalMajorVersion="1"InternalMinorVersion="0"> <ARTSHeader ActionCode="Calculate" MessageType="Request"> <MessageID>9a89f2edfd1e413ea147e334b9c2ed4b</MessageID> <DateTime>2250-01-13T04:48:30.427-05:00</DateTime> <BusinessUnit TypeCode="RetailStore">FC01</BusinessUnit> </ARTSHeader>

<PriceCalculateBody TransactionType="SaleTransaction" NetPriceFlag="true"> <TransactionID>9a89f2edfd1e413ea147e334b9c2ed4b</TransactionID> <DateTime>2250-01-13T04:48:30.427-05:00</DateTime> <ShoppingBasket> <LineItem> <SequenceNumber>0</SequenceNumber> <MerchandiseHierarchy ID="1">CHA2111</MerchandiseHierarchy> <Sale ItemType="Stock" NonDiscountableFlag="false" FixedPriceFlag="false"> <TaxIncludedInPriceFlag>false</TaxIncludedInPriceFlag> <NonPieceGoodFlag>false</NonPieceGoodFlag>

<FrequentShopperPointsEligibilityFlag>true</FrequentShopperPointsEligibilityFlag> <NotConsideredByPriceEngineFlag>false</NotConsideredByPriceEngineFlag> <ItemID>CHA2111001</ItemID> <Quantity Units="1" UnitOfMeasureCode="PCE">2</Quantity> </Sale> </LineItem> </ShoppingBasket> </PriceCalculateBody></PriceCalculate>

Code Block 1 Sample 1: Simple request in XML format

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 11

4.2 Response structure

After a successful call, the PCE returns the response in a PriceCalculateResponse object (for example,com.sap.ppengine.client.dto.PriceCalculateResponse) and informs the client about the status using aResponseCode.

Below you see the response to the request presented in sample 1.

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><PriceCalculateResponse xmlns="http://www.sap.com/IXRetail/namespace/"InternalMajorVersion="1" InternalMinorVersion="0"> <ARTSHeader ActionCode="Calculate" MessageType="Response"> <MessageID>471b53ba-958e-4f8b-804c-d690e1c3f6d7</MessageID> <DateTime>2017-04-10T09:29:27.862+02:00</DateTime> <Response ResponseCode="OK"> <RequestID>9a89f2edfd1e413ea147e334b9c2ed4b</RequestID> <ResponseTimestamp>2250-01-13T04:48:30.427-05:00</ResponseTimestamp> </Response> <BusinessUnit TypeCode="RetailStore">FC01</BusinessUnit> </ARTSHeader> <PriceCalculateBody TransactionType="SaleTransaction" NetPriceFlag="true"> <TransactionID>9a89f2edfd1e413ea147e334b9c2ed4b</TransactionID> <DateTime>2250-01-13T04:48:30.427-05:00</DateTime> <ShoppingBasket> <LineItem> <Sale ItemType="Stock" NonDiscountableFlag="false" FixedPriceFlag="false"> <ItemID>CHA2111001</ItemID> <ExtendedAmount>0.0</ExtendedAmount> <ExtendedDiscountAmount>0.0</ExtendedDiscountAmount> <Quantity Units="1.0" UnitOfMeasureCode="PCE">2</Quantity> <TaxIncludedInPriceFlag>false</TaxIncludedInPriceFlag> <NonPieceGoodFlag>false</NonPieceGoodFlag>

<FrequentShopperPointsEligibilityFlag>true</FrequentShopperPointsEligibilityFlag> <PriceTypeCode>00</PriceTypeCode> <NotConsideredByPriceEngineFlag>false</NotConsideredByPriceEngineFlag> </Sale> <SequenceNumber>0</SequenceNumber> <MerchandiseHierarchy ID="1">CHA2111</MerchandiseHierarchy> </LineItem> </ShoppingBasket> </PriceCalculateBody></PriceCalculateResponse>

Code Block 2 Sample 2: Response to request in code sample 1

If a valid request is sent with unexpected values or structure, the PCE will inform the client through aBusiness Error Code in the response header section. You find a description of the Business Error Codes forthe concrete error cases in chapter "Business Error Codes". The Business Error Code is returned as part ofthe ARTSHeader element in the response message.

SDK Promotion Calculation Engine12 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

See the following example for details:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><PriceCalculateResponse xmlns="http://www.sap.com/IXRetail/namespace/"InternalMajorVersion="1" InternalMinorVersion="0"> <ARTSHeader ActionCode="Calculate" MessageType="Response"> <MessageID>0b15d202-5536-4b1c-bd1e-06f8beee72ba</MessageID> <DateTime>2017-04-10T09:38:09.894+02:00</DateTime> <Response ResponseCode="Rejected"> <RequestID>9a89f2edfd1e413ea147e334b9c2ed4b</RequestID> <ResponseTimestamp>2017-04-10T09:38:09.893+02:00</ResponseTimestamp> <BusinessError Severity="Error"> <ErrorID>GKR-100500</ErrorID> <Description>Value not supported. Element LineItem.SequenceNumber. Sent: -10. Expected: 0.</Description> </BusinessError> </Response> <BusinessUnit TypeCode="RetailStore">FC01</BusinessUnit> </ARTSHeader> <PriceCalculateBody TransactionType="SaleTransaction" NetPriceFlag="true"> <TransactionID>9a89f2edfd1e413ea147e334b9c2ed4b</TransactionID> <DateTime>2250-01-13T04:48:30.427-05:00</DateTime> <ShoppingBasket> <LineItem> <Sale ItemType="Stock" NonDiscountableFlag="false" FixedPriceFlag="false"> <ItemID>CHA2111001</ItemID> <Quantity Units="1" UnitOfMeasureCode="PCE">2</Quantity> <TaxIncludedInPriceFlag>false</TaxIncludedInPriceFlag> <NonPieceGoodFlag>false</NonPieceGoodFlag>

<FrequentShopperPointsEligibilityFlag>true</FrequentShopperPointsEligibilityFlag> <NotConsideredByPriceEngineFlag>false</NotConsideredByPriceEngineFlag> </Sale> <SequenceNumber>-10</SequenceNumber> <MerchandiseHierarchy ID="1">CHA2111</MerchandiseHierarchy> </LineItem> </ShoppingBasket> </PriceCalculateBody></PriceCalculateResponse>

Code Block 3 Business Error Code GKR-100500 (unexpected value)

4.3 Calculation modes

The PCE currently supports two calculation modes: Basket and LineItem. The calculation mode controls howthe PCE interprets and processes the incoming request, which causes different expected results as well.Calculation modes are supported since interface version 2 (that is, InternalMajorVersion="2"). In bothmodes, there is no constraint to which kinds of promotions can be applied (for example, coupons, manualrebates, promotion buy 3 pay 3, etc). If a promotion is loaded and eligible, it will be handled, analyzed, andapplied either for basket or line item mode.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 13

4.3.1 Basket mode

The calculation mode Basket is the default way to analyze and calculate transactions. All line items areconsidered and processed at the same time. For example, in a transaction with 10 items, each costs 1 €, atransaction coupon of 3 € rebate will be applied and prorated to all items, producing a total price of 7 €.Basket mode can be explicitly defined in the attribute CalculationMode of the request message'sPriceCalculateBody element.

See example below:

<PriceCalculateBody TransactionType="SaleTransaction" NetPriceFlag="true"CalculationMode="Basket">

Code Block 4 CalculationMode

4.3.2 LineItem mode

In Line Item mode, all line items in the transaction are handled and processed separately. This means that allline items in the request will be split and processed by the PCE independently and the individual results willbe summarized in the end. For example, in a transaction with 10 items, each costs 1 €, a transaction couponof 3 € rebate will not be applied because every item is processed separately and this way the price (1€) isless than the rebate of 3€.

Line Item mode can be explicitly defined/requested using the attribute CalculationMode of the requestmessage's PriceCalculateBody element.

See example below:

<PriceCalculateBody TransactionType="SaleTransaction" NetPriceFlag="true"CalculationMode="LineItem">

Code Block 5 CalculationMode

SDK Promotion Calculation Engine14 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

5 How the PCE works

In order to achieve the expected results, the PCE executes a series of well-defined steps. The following figuredemonstrates these execution steps:

You find a detailed explanation of these steps in the following section.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 15

5.1 Request processing

The process starts when the system receives a request of type PriceCalculate. In the phase of Parse request,the request is validated and mapped to internal Java models with the help of a data mapper object.Afterwards, an instance of Pricing Engine is created. Pricing Engine is called passing through a Pricing Enginerequest containing configuration data and the mapped request.

Parse request: The request of type PriceCalculate is parsed, validated, and mapped to internal object modelsto be processed. Validations are done in this step, for example, check data format integrity, check correlativesequence numbers, check constraints regarding to max permitted values, etc. If something is wrongaccording to specification, a business error is produced and the execution is interrupted.

Create Pricing Engine instance: An instance of Pricing Engine is created with the help of a Pricing Enginefactory class.

Call Pricing Engine: Call Pricing Engine main method process passing through a Pricing Engine request thatcontains configuration data and mapped request. At this step, the called calculation mode is checked. If lineitem mode is requested, the line item will be split into separate transactions to be processed independently.Otherwise, the default basket mode is used and the transaction with all line items from the request isprocessed as a whole.

Initialize PCE context: All information during the analysis and calculation is stored into a PCE context. ThePCE context is available during the whole calculation process and updated as needed. This step ensures thatall initially available information is stored.

Clean promotion data from transaction: Useful for line item mode where the line items are processedindependently. Cleans the PCE context and makes sure that no information of a finished process interfereswith the process of the next line item.

Analyze transaction: Phase of analysis where every line item is analyzed and classified. The analyzers aresplit by functionalities and can be easily extended by implementing the interface TransactionAnalyzer. Everyanalyzer has to store information in the PCE context.

Currently implemented analyzers are:

· Coupon transaction analyzer: Responsible for processing and storing coupons from the request.

· Customer group transaction analyzer: Responsible for looking for customer group-related items.

· External promotion transaction analyzer: Responsible for looking for external promotions likeexternal price modifiers, external line items, loyalty reward or price derivation rules.

· Item transaction analyzer: Responsible for extracting line item basket values, transaction totalbasket values, finding and processing of related merchandise hierarchy groups.

· Promotion manual trigger analyzer: Responsible of looking for manual triggers related to line itemposition as well as transaction level rebates.

SDK Promotion Calculation Engine16 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Normalize transaction: Line items are normalized according to their quantity. For instance, if a transactioncontains a line item with quantity 10, the result of normalized process will be a transaction with 10 line itemswith quantity 1. This ensures uniform results of the price calculation, regardless of the structure of thetransaction.

5.2 Eligibility loading

Eligibilities are the triggers for applying a promotion. Eligibilities contain all necessary information thatenables the PCE to determine whether a promotion is applicable on a certain line item. A promotion mustcontain at least one eligibility. The eligibilities are loaded from the data access layer.

Similar to the analyzer, the eligibility loader is split into well-defined functionalities. Each loader isresponsible for loading different types of eligibilities from the data access layer and for activating andregistering them into the PCE context.

· Coupon eligibility loader

· Item eligibility loader

· Merchandise group eligibility loader

· Merchandise set eligibility loader

· Market basket amount eligibility loader

· Customer group eligibility loader

· Manual trigger eligibility loader

Some common steps are explained below:

Load eligibilities: Eligibilities are loaded from the persistence layer.

Fill item buckets: Based on the analyzed data, the item bucket is saved into the PCE context.

Check loaded eligibilities and activate eligibility: Check if items apply to eligibility, if true, the eligibility isactivated.

Check and activate parent eligibility: If an eligibility has a parent eligibility, it will also be checked andactivated if the item conditions are fulfilled.

5.3 Promotion calculation

This phase is responsible for calculating promotions for the transaction, applying rebates (price modifiers,coupon), frequent shopper points modifiers, calculated loyalty reward items, etc. Based on the analyzed

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 17

data, conditions for activated eligibilities, and promotions are loaded from data access layer, validated andcalculated to positions if applicable.

The related steps are explained below:

· Load conditions for activated eligibility: Conditions for activated eligibilities are loaded from dataaccess layer.

· Load related promotions: Promotion information is loaded from data access layer.

· Check promotion validity: Check validity for loaded promotions.

· Order conditions by sequence: Conditions are ordered by sequence number.

· Calculate position conditions: For every transaction position (line item) it is necessary to calculatethe related promotion.

· Apply to position summary results: After the calculation is performed, the resulting information issaved into the position summary result.

· Calculate transaction conditions: Calculate all related promotions for transaction level.

· Apply transaction summary result: After the calculation on transaction level is finished, the resultinginformation is saved into the transaction summary result.

5.4 Update transaction

After performing all calculations, the transaction will be updated. This phase is responsible for updating atransaction and line items with the calculated promotions and related information (for example, positionand transaction partial results).

The related steps are explained below:

· Prorate transaction rebates: If a rebate exists, it is prorated to all related items in the transaction.

· Summarize price modifiers: Price modifiers are summarized and added to the affected line items.

· Update transaction: Transaction and line items are updated.

5.5 Create response

The calculated data is mapped back to a response object and sent back to the calling process.

SDK Promotion Calculation Engine18 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

5.6 Bucket calculation

The following image explains the bucket calculation algorithm:

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 19

6 The data access layer (DAL)

The data access layer (DAL) entirely encapsulates the access to the master data provider to load promotiondata and map it to model data objects.

The DAL consists of the following modules:

· DataAccessService: Main interface which has to be implemented. The implementation is provided bySAP.

· DataProvider: Vendor-specific component to load data, for example, from the database. Theimplementation is provided by SAP.

· DataMapping: Component which is called after retrieving objects from the data provider to map tointernal model objects.

The main DAL component interaction is shown in the following figure:

SDK Promotion Calculation Engine20 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 21

7 How to extend the PCE

The previously described steps executed by the PCE can be extended.

The following figure gives an overview of the process:

7.1 PCE Context

The PCE context is responsible for storing and exposing all data extracted and analyzed in the phases of aPCE process. The PCE Context helps to carry out this information between processes and the process thatuses it to read and update content. The PCE Context is defined in the interface PCE Context

SDK Promotion Calculation Engine22 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

(com.gk_software.pricing_engine.api.context.Context) and implemented in ContextImpl(com.gk_software.pricing_engine.api.context.ContextImpl). The context is passed as a parameter on all phases ofthe PCE process.

More specifically, the content stores the following information:

· Transaction analyzer context

· Eligibility loader context

· Promotion condition context

· Configuration

· Transaction and retail transaction line items

· Position and transaction relevant line items

· Business unit group

· Position and transaction summary results

· Partial results

· Manual promotions triggers

· Some important flags

7.2 Object factories and how to extend them

The PCE uses factories to centralize the way of creating objects and their default values. All factories containthe word factory in the Java class name.

The implementation of a new object factory must be performed in the following way:

1. There are two ways to create a new factory class:a. Create a new class which implements a specific factory interface.b. Create a new class which extends the corresponding default factory implementation.

2. Override an existing method using standard Java @override annotations to provide extended objects.3. Add new methods to create new custom objects.

Please note that when a new interface method is established, the customer is responsible to provide animplementation. It is highly recommended to extend and not create a new factory to avoid problems withwell-defined functionalities.

An example can be seen in the following code sample:

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 23

package some.extension.package_name;public class CustomPricingEngineObjectFactory extends PricingEngineDefaultObjectFactoryimplements PricingEngineObjectFactory { /** * Override existing createContext to create own custom context */ @Override public Context createContext() { return new CustomContext(); } /** * New custom method to create custom object. */ public CustomObject createCustomObject() { return new CustomObject(); }}

Code Block 6 Custom factory

To register the custom factory bean, override the existing configuration as follows:

<!-- bean definition of CustomPricingEngineObjectFactory --><alias name="customPricingEngineObjectFactory" alias="pricingEngineObjectFactory"/><bean id="customPricingEngineObjectFactory"class="some.extension.package_name.CustomPricingEngineObjectFactory" />

7.3 Transaction analyzer

The purpose of the transaction analyzer is to check the sales transaction for certain data needed for furtherprocessing like loading of eligibilities or calculation of rules. The results are stored in the PCE Context in fieldtransactionAnalyzerContext.

Examples for transaction analyzers:

· ItemTransactionAnalyzer: Analyzes the registered line items and stores cumulated data based onitem ids and merchandise hierarchy group ids to the PCE Context.

SDK Promotion Calculation Engine24 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

· CouponTransactionAnalyzer: Checks whether coupons are registered within the transaction andstores the result to a structure in the PCE Context. The result is stored inContext.transactionAnalyzerContext.couponNumberSet.

· CustomerGroupTransactionAnalyzer: Checks whether customer groups are defined for registeredcustomers. The result is stored in Context.transactionAnalyzerContext.customerGroupIDSet.

7.3.1 Spring bean configuration

All analyzers must be defined as single beans in the Spring application context which are consolidated in aspecific list with bean id transactionAnalyzerList.

This list bean definition is injected to the Pricing Engine bean and the analyzers are executed in the orderthey are specified.

Therefore, this list must be replaced when analyzers shall be removed/exchanged or added.

<util:list id="transactionAnalyzerList" list-class="java.util.ArrayList"><ref bean="itemTransactionAnalyzer"/><ref bean="externalPromotionsTransactionAnalyzer"/><ref bean="couponTransactionAnalyzer"/><ref bean="customerGroupTransactionAnalyzer"/><ref bean="promotionManualTriggerAnalyzer"/>

</util:list>

7.3.2 Add a new transaction analyzer and register it

The following steps must be performed to create and add a new transaction analyzer:

Create a new class which implements the interface com.gk_software.pricing_engine.api.TransactionAnalyzer:

package some.extension.package_name;public class CustomCouponTransactionAnalyzer implements TransactionAnalyzer {

@Override public void analyzeTransaction(Context context) { // do something }}

Add a bean definition in the Spring application context for the new analyzer:

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 25

<bean id="customCouponTransactionAnalyzer"class="some.extension.package_name.CustomCouponTransactionAnalyzer"> ...</bean>

Overwrite the transactionAnalyzerList bean and add a reference to the analyzer:

<util:list id="transactionAnalyzerList" list-class="java.util.ArrayList"> <ref bean="itemTransactionAnalyzer"/> <ref bean="externalPromotionsTransactionAnalyzer"/> <ref bean="customCouponTransactionAnalyzer"/> <!-- replaced couponTransactionAnalyzer --> <ref bean="customerGroupTransactionAnalyzer"/></util:list>

7.4 Eligibility loader

The purpose of EligibilityLoader is to check/load eligibilities based on precalculated data from transactionanalyzers.

Examples for eligibility loaders:

· CouponEligibilityLoader: Tries to find CouponPromotionConditionEligibilitySO for the collected coupondata stored in TransactionAnalyzerContext->getCouponNumberSet(). If one exists, it will be activated.

· CustomerGroupEligibilityLoader: Tries to find CustomerGroupPromotionConditionEligibilitySO forcollected coupon data stored in TransactionAnalyzerContext->getCustomerGroupIDSet(). If one exists, itwill be activated.

7.4.1 Spring bean configuration

All eligibility loaders are defined as single beans in the Spring application context which are consolidated in aspecific list with bean id eligibilityLoaderList.

This list bean definition is injected to the Pricing Engine bean in the Spring bootstrap phase.

The currently registered eligibility loaders can be viewed as follows:

<util:list id="eligibilityLoaderList" list-class="java.util.ArrayList"> <ref bean="couponEligibilityLoader"/>

SDK Promotion Calculation Engine26 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

<ref bean="itemEligibilityLoader"/> <ref bean="merchandiseGroupEligibilityLoader"/> <ref bean="merchandiseSetEligibilityLoader"/> <ref bean="marketBasketAmountEligibilityLoader"/> <ref bean="customerGroupEligibilityLoader"/> <ref bean="manualTriggerEligibilityLoader"/></util:list>

7.4.2 Add a new eligibility loader and register it or extend a existing

You can create a new eligibility: Just define a new bean, implement it, and add it to the list defined in theXML bean definition file. It is also possible to simply extend an existing bean (using Java extend, for example,public class MySpecialEligibilityLoader extends CouponEligibilityLoader) and put the definition in the XML withthe same alias. Do not forget to delete the old one or deactivate it (for example, by commenting it out).

The following steps must be performed in order to create and add a new eligibility loader:

Create a new class which implements the interface com.gk_software.pricing_engine.api.EligibilityLoader:

package some.extension.eligibility_loader;public class CustomXYZEligibilityLoader implements EligibilityLoader {

private CustomDataAccessService customDataAccessService;

@Override public void execute(Context context) { ... List<CustomXYZEligibilitySO> loadedEligibilities =this.customDataAccessService.getCustomXYZEligibilities(context, ...); ... }

public void setCustomDataAccessService(CustomDataAccessService customDataAccessService){ this.customDataAccessService = customDataAccessService; }}

Add a bean definition in the Spring application context for the new loader:

<bean id="customXYZEligibilityLoader"class="some.extension.eligibility_loader.CustomXYZEligibilityLoader"> <property name="customDataAccessService" ref="customDataAccessService" />

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 27

...</bean>

Extend the eligibilityLoaderList bean and add a reference to the loader:

<util:list id="eligibilityLoaderList" list-class="java.util.ArrayList"> <ref bean="couponEligibilityLoader"/> <ref bean="itemEligibilityLoader"/> <ref bean="merchandiseGroupEligibilityLoader"/> <ref bean="merchandiseSetEligibilityLoader"/> <ref bean="marketBasketAmountEligibilityLoader"/> <ref bean="customerGroupEligibilityLoader"/> <ref bean="manualTriggerEligibilityLoader"/> <ref bean="customXYZEligibilityLoader" /> <!-- new custom eligibility loader --></util:list>

Finally, restart your application to load and populate the list again.

7.5 Calculation Rules (Discount operations)

The purpose of Calculation Rule is to indicate discount operations and modify the base flow based oncalculation rules (in Java RuleType class).

Examples for condition rules:

· MixAndMatchCalculationRule: Performs operations and modifies the base flow based on mix andmatch rules (RuleType.MM).

· SimpleDiscountCalculationRule: Performs operations and modifies the base flow based on simplediscount rules (RuleType.RB).

The following figure shows a class diagram of CalculationRule:

SDK Promotion Calculation Engine28 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

A rule is applied if - and only if - a condition is satisfied. For example, to apply a fully-priced item promotion,the following conditions must be fulfilled:

· A promotion which is allowed for fully-priced items can only be applied for the item if no othermonetary promotion was applied for the item before it.

· A promotion which is allowed for fully-priced items only cannot be applied for the item if one ormore monetary promotions were applied for the item before it.

Example: A customer has three items in his shopping basket: item 1, item 2 and item 3. Item 2 is on sale witha 50% discount. There is a promotion in place, which entitles the customer to a 10% discount on all items inhis shopping basket. This promotion, however, is only applicable on “fully-priced items”. This means thecustomer will get 10% off on item 1 and item 3, but not on item 2, as item 2 was already reduced by 50% byanother promotion applied before.

The condition information is stored and retrieved from the DAL.

7.5.1 Spring bean configuration

All condition rules must be defined as single beans in the Spring application context which are consolidatedin a specific list with bean id calculationRules.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 29

This list bean definition is injected to conditionLoader bean.

Therefore, this list must be replaced when condition rules shall be removed/exchanged or added.

<util:list id="calculationRules" list-class="java.util.ArrayList"> <ref bean="externalActionCalculationRule"/> <ref bean="get3Pay2CalculationRule"/> <ref bean="manualPriceCalculationRule"/> <ref bean="mixAndMatchCalculationRule"/> <ref bean="noDiscountCalculationRule"/> <ref bean="simpleDiscountCalculationRule"/></util:list>

The CalculationRule uses the PriceModificationFacade in order to calculate the price reduction based on theprice modification methods.

It is also injected in the Spring context as can be seen in the following code sample:

<bean id="abstractCalculationRule"class="com.gk_software.pricing_engine.rule_type.AbstractCalculationRule" abstract="true" > <property name="priceModificationFacade" ref="priceModificationFacade" /> <property name="dataAccessService" ref="dataAccessService" /></bean><bean id="abstractItemCalculationRule"class="com.gk_software.pricing_engine.rule_type.AbstractItemCalculationRule"parent="abstractCalculationRule" abstract="true" /><bean id="externalActionCalculationRule"class="com.gk_software.pricing_engine.rule_type.ExternalActionCalculationRule"parent="abstractItemCalculationRule" /><bean id="get3Pay2CalculationRule"class="com.gk_software.pricing_engine.rule_type.Get3Pay2CalculationRule"parent="abstractCalculationRule" /><bean id="manualPriceCalculationRule"class="com.gk_software.pricing_engine.rule_type.ManualPriceCalculationRule"parent="abstractItemCalculationRule" /><bean id="mixAndMatchCalculationRule"class="com.gk_software.pricing_engine.rule_type.MixAndMatchCalculationRule"parent="abstractCalculationRule" /><bean id="noDiscountCalculationRule"class="com.gk_software.pricing_engine.rule_type.NoDiscountCalculationRule"parent="abstractCalculationRule" /><bean id="simpleDiscountCalculationRule"class="com.gk_software.pricing_engine.rule_type.SimpleDiscountCalculationRule"parent="abstractItemCalculationRule" />

SDK Promotion Calculation Engine30 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

7.6 Add and register a new calculation rule

The following steps must be performed to create and add a new calculation rule:

Create a new class which implements the interfacecom.gk_software.pricing_engine.api.rule_type.CalculationRule:

package some.extension.rule_type;public class CustomXYZCalculationRule implements CalculationRule {

private CustomCalculationRule customDataAccessService;

@Override public PromotionConditionRuleSO loadPromotionConditionRule(Context context, long ruleID){ return customDataAccessService.getExternalActionRule(ruleID); }

@Override public String getPriceModificationMethodCode(PromotionConditionRuleSOpromotionConditionRuleSO) { return PriceModificationMethodCode.NEW_RULE; }

public void setCustomDataAccessService(CustomDataAccessService customDataAccessService){ this.customDataAccessService = customDataAccessService; }}

Add a bean definition in the Spring application context for the new calculation rule:

<bean id="customXYZCalculationRule "class="some.extension.rule_type.CustomXYZCalculationRule "> <property name="customDataAccessService" ref="customDataAccessService" /> ...</bean>

Register the calculationRules bean and add a reference to the newly created calculation rule:

<util:list id="calculationRules" list-class="java.util.ArrayList"> <ref bean="externalActionCalculationRule"/> <ref bean="get3Pay2CalculationRule"/> <ref bean="manualPriceCalculationRule"/> <ref bean="mixAndMatchCalculationRule"/> <ref bean="noDiscountCalculationRule"/>

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 31

<ref bean="simpleDiscountCalculationRule"/> <ref bean="customXYZCalculationRule"/> <!-- new custom calculation rule --></util:list>

7.7 Price Modification

The purpose of PriceModification is to perform calculations based on price modification methods(PriceModificationMethod and ReductionMethodMixAndMatch).

Examples for price modifications:

· PercentageDiscountPriceModification: Performs percentage discount calculations(PriceModificationMethod.RP).

· AbsoluteDiscountPriceModification: Performs absolute discount calculations(PriceModificationMethod.RS).

The Price Rules indicate a discount (for example, percent rebate, single reduction, single price).PriceModification is responsible for performing the calculation based on the current partial results.

The following figure shows a class diagram of PriceModification:

SDK Promotion Calculation Engine32 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

7.7.1 Spring bean configuration

All price modifications must be defined as single beans in the Spring application context which areconsolidated in specific list with bean id eligibilityLoaderList.

This list bean definition is injected to Pricing Engine bean.

Therefore, this list must be replaced when eligibility loaders shall be removed/exchanged or added.

<util:list id="priceModifications" list-class="java.util.ArrayList"> <ref bean="absoluteDiscountPriceModification"/> <ref bean="newPricePriceModification"/> <ref bean="newTotalPricePriceModification"/> <ref bean="newSetPricePriceModification"/> <ref bean="totalAbsoluteDiscountPriceModification"/> <ref bean="totalPercentageDiscountPriceModification"/> <ref bean="totalPercentageDiscountRoundedTwicePriceModification"/> <ref bean="percentageDiscountPriceModification"/> </util:list>

7.7.2 Add and register a new price modification

The following steps must be performed to create and add a new price modification:

Create a new class which implements the interfacecom.gk_software.pricing_engine.price_modification_engine.PriceModification:

package some.extension.price_modification;public class CustomXYZPriceModification implements PriceModification {

@Override public EPriceModificationMethod getPriceModificationMethod() { return EPriceModificationMethod.NEW; }

@Override public RuleCalculationResult calculatePositionNonTotalConditionValue(Context context,BigDecimal usedQuantity, BigDecimal usedAmount, PartialResult partialResult, LineItemSummaryResultlineItemSummaryResult, BigDecimal positionQuantity) { ... }}

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 33

Add a bean definition in the Spring application context for the price modification:

<bean id="customXYZPriceModification"class="some.extension.price_modification.CustomXYZPriceModification" />

Overwrite the priceModifications bean and add a reference to the newly created price modification:

<util:list id="priceModifications" list-class="java.util.ArrayList"> <ref bean="absoluteDiscountPriceModification"/> <ref bean="newPricePriceModification"/> <ref bean="newTotalPricePriceModification"/> <ref bean="newSetPricePriceModification"/> <ref bean="totalAbsoluteDiscountPriceModification"/> <ref bean="totalPercentageDiscountPriceModification"/> <ref bean="totalPercentageDiscountRoundedTwicePriceModification"/> <ref bean="percentageDiscountPriceModification"/> <ref bean="customXYZPriceModification"/> <!-- new price modification --> </util:list>

7.8 Transaction update handler

The TransactionUpdateHandler is responsible for cleaning promotional data and creating promotional data inthe transaction. This means the item or transaction will be extended with additional information aboutapplied promotions/discounts if existing. This information is shown in the response as RetailPriceModifier.

The TransactionUpdateHandler is called in the following phases:

· Before processing: The already applied promotional data is removed from the transaction. Forexample, normal RetailPriceModifier/FrequentShopperPointsModifier.

· After processing: The calculated data is written back to the transaction. For example,PriceModificationLineItems/LoyaltyRewardLineItems are created.

The transaction update handler can be seen in the following figure:

SDK Promotion Calculation Engine34 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

7.8.1 Spring configuration

Like every bean, the transaction update handler is registered in the beans.xml file.

<bean id="transactionUpdateHandler"class="com.gk_software.pricing_engine.api.transaction.TransactionUpdateHandlerDelegate"> <property name="delegate" ref="transactionUpdateHandlerImpl"/> </bean> <bean id="transactionUpdateHandlerImpl"class="com.gk_software.pricing_engine.transaction_service.TransactionUpdateHandlerImpl"> <constructor-arg ref="transactionDOServiceLE"/> <constructor-arg ref="transactionCalculationServiceLE"/> </bean>

Note: TransactionCalculationService and TransactionDomainObjectService are simply utility services that help toperform calculations (for example, calculate extra amount) and create domain objects (for example, retailprice modifier).

7.8.2 Exchange TransactionUpdateHandler

The following steps must be performed to exchange the TransactionUpdateHandler:

Create a new custom TransactionUpdateHandler.

This can be performed in two different ways:

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 35

7.8.2.1 Implement a new TransactionUpdateHandler

Create a CustomTransactionHandler which implements the interfacecom.gk_software.loyalty_engine.api.transaction.TransactionUpdateHandler:

package com.gk_software.pricing_engine.api.transaction;

import com.gk_software.pricing_engine.api.context.Context;

public class CustomTransactionUpdateHandler implements TransactionUpdateHandler {

@Override public void clearPromotionDataFromTransaction(Context context) { // so something }

@Override public void createPriceDerivationRules(Context context) { // so something }

@Override public void createPriceModificationLineItems(Context context) { // so something }

@Override public void createLoyaltyRewardLineItems(Context context) { // so something }

@Override public void updateLineItems(Context context) { // so something }}

7.8.2.2 Extend existing delegate

Extend TransactionUpdateHandlerDelegate and overwrite the desired methods:

package project.pricing_engine.transaction;public class CustomTransactionUpdateHandlerDelegate extends TransactionUpdateHandlerDelegate{

@Override public void createPriceDerivationRules(Context context) {

SDK Promotion Calculation Engine36 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

this.delegate.createPriceDerivationRules(context);

// do some post processing }}

7.8.2.3 Override bean definition in Spring application context for thedefault delegate

<bean id="customTransactionUpdateHandler"class="project.pricing_engine.transaction.CustomTransactionUpdateHandlerDelegate "> <property name="delegate" ref="transactionUpdateHandlerImpl" /> ...</bean>

7.9 List of all beans in pricing engine impl

Every bean loaded in the Pricing Engine and the corresponding aliases are shown below:

ID Alias Description

gkDefaultPricingEngineObjectFactory pricingEngineObjectFactory Contains methods for creation ofcalculation-related PricingEngine objects.

gkPricingEngineObjectFactoryProvider - FactoryProvider to accesspricingEngineObjectFactoy as singleton.

gkDefaultPromotionSOFactory promotionSOFactory Factory for promotion master data modelDTOs.

gkDefaultTransactionFactory transactionFactory Factory for transaction (client) model DTOs.

gkDefaultItemTransactionAnalyzer itemTransactionAnalyzer Analyzes items in transaction and storesthe result to the PCE Context.

gkDefaultExternalPromotionsTransactionAnalyzer

externalPromotionsTransactionAnalyzer

Analyzes external promotions intransaction and stores the result to thePCE Context.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 37

ID Alias Description

gkDefaultCouponTransactionAnalyzer couponTransactionAnalyzer Analyzes coupons in transaction data andstores the result to the PCE Context.

gkDefaultCustomerGroupTransactionAnalyzer customerGroupTransactionAnalyzer

Analyzes customer group data intransaction and stores the result to thePCE Context.

gkDefaultPromotionManualTriggerAnalyzer promotionManualTriggerAnalyzer Analyzes manual triggers in transactionand stores the result to the PCE Context.

gkTransactionAnalyzerList transactionAnalyzerList List of transaction analyzers to use inpricing-engine.

abstractEligibilityLoader -

gkDefaultCouponEligibilityLoader couponEligibilityLoaderCoupon eligibility loader. It tries to loadCouponPromotionConditionEligibility forcollected coupon data and activates it.

gkDefaultItemEligibilityLoader itemEligibilityLoaderItem eligibility loader. It tries to loadItemPromotionConditionEligibilitySO forcollected item data and activates it.

gkDefaultMerchandiseGroupEligibilityLoader merchandiseGroupEligibilityLoader

Merchandise Hierarchy Group eligibilityloader. It tries to loadMHGPromotionConditionEligibility forcollected mhg item data and activates it.

gkDefaultMerchandiseSetEligibilityLoader merchandiseSetEligibilityLoader

Merchandise Set eligibility loader. It tries toloadMerchandiseSetPromotionConditionEligibility for collected item data and activates it.

gkDefaultMarketBasketAmountEligibilityLoader marketBasketAmountEligibilityLoader

MarketBasketAmount eligibility loader. Ittries to loadMarketBasketAmountPromotionConditionEligibility based on calculated transactiontotal and activates it.

gkDefaultCustomerGroupEligibilityLoader customerGroupEligibilityLoader

Customer group eligibility loader. It tries toloadCustomerGroupPromotionConditionEligibility based on collected customer data andactivates it.

gkDefaultManualTriggerEligibilityLoader manualTriggerEligibilityLoader

Manual Trigger eligibility loader. It tries toloadManualTriggerPromotionConditionEligibilitybased on collected manual triggers andactivates it.

gkEligibilityLoaderList eligibilityLoaderList

gkDefaultPricingEngineFactory pricingEngineFactory Factory for creating and initializing aPricingEngine instance.

SDK Promotion Calculation Engine38 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

ID Alias Description

gkDefaultContextProviderFactory contextProviderFactoryContext Provider for accessing the PCEContext i.e. as ThreadLocal mode for multi-threaded environments.

gkDefaultConfigurationInitializer configurationInitializerParser for initializing configuration fromdata passed in request or externalconfiguration.

transactionUpdateHandler - Updates internal pricing engine transactionmodel with calculation results.

transactionUpdateHandlerImpl -

transactionSplitter - Splits transaction in multiple single itemtransactions for line item calculation.

gkDefaultConditionLoader conditionLoader Loads active conditions and stores theresult to the PCE Contexts.

resolutionComparator -

gkDefaultPromotionCalculator promotionCalculatorThe PromotionCalculator is the main entrypoint to promotion calculation called by thePricingEngine.

dataAccessService -Dummy DataAccessService delegate. Willbe overwritten by concrete data accessimplementation.

calculatorPositionPartialService - Internal calculation bean for handlingposition based promotions.

calculatorTransactionPartialService - Internal calculation bean for handlingtransaction based promotions.

transactionDOServiceLE -Helper bean for TransactionUpdateHandlerto transforming calculation results intomodel objects.

transactionCalculationServiceLE -Service to perform additional transactionrelated calculations like subtotalcalculation.

eligibilityService - Internal service for additional Eligibilityrelated operations.

gkPriceModifications priceModifications List of price modification calculations.

abstractPriceModification -

absoluteDiscountPriceModification -

newPricePriceModification -

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 39

ID Alias Description

newTotalPricePriceModification -

newSetPricePriceModification -

totalAbsoluteDiscountPriceModification -

totalPercentageDiscountPriceModification -

totalPercentageDiscountRoundedTwicePriceModification -

percentageDiscountPriceModification -

gkPriceModificationFacade priceModificationFacade Facade that provides unified interface toall price modifications.

gkCalculationRules calculationRules List of price rule calculations.

abstractCalculationRule - Abstract bean definitions for calculationrules.

abstractItemCalculationRule -

externalActionCalculationRule - Calculates rebates for External ActionRules.

get3Pay2CalculationRule - Calculates rebates for Get3Pay2 (BOGO)Rules.

manualPriceCalculationRule - Calculates rebates for Manual rules.

mixAndMatchCalculationRule - Calculates rebates for MixAndMatch rules.

noDiscountCalculationRule - Calculates dummy rebates for no discountrules.

simpleDiscountCalculationRule - Calculates rebates for all simple rebaterules (ItemRebate, TransactionRebate).

calculationEngineProvider - Provides calculation engine for processingmathematical operations.

SDK Promotion Calculation Engine40 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

8 Business Error Codes

To inform the caller about input that is not well-formed or unexpected behavior while processing a request,Business Error Codes were defined for the different possible error scenarios. Business Error Codes are sentback in the response object and packed into the ARTS header.

See the following example for details:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?><PriceCalculateResponse xmlns="http://www.sap.com/IXRetail/namespace/"InternalMajorVersion="2" InternalMinorVersion="0"> <ARTSHeader ActionCode="Calculate" MessageType="Response"> <MessageID>ee2c780a-a44e-4c4e-a8e3-eede4484caff</MessageID> <DateTime>2017-04-12T16:14:22.483+02:00</DateTime> <Response ResponseCode="Rejected"> <RequestID>9a89f2edfd1e413ea147e334b9c2ed4b</RequestID> <ResponseTimestamp>2017-04-12T16:14:22.482+02:00</ResponseTimestamp> <BusinessError Severity="Error"> <ErrorID>GKR-100500</ErrorID> <Description>Value not supported. Element LineItem.SequenceNumber. Sent: 55.Expected: 0.</Description> </BusinessError> </Response> <BusinessUnit TypeCode="RetailStore">OS01</BusinessUnit> </ARTSHeader> <PriceCalculateBody TransactionType="SaleTransaction" NetPriceFlag="true"CalculationMode="LineItem"> <TransactionID>9a89f2edfd1e413ea147e334b9c2ed4b</TransactionID> <DateTime>2501-03-09T00:00:00.000Z</DateTime> <ShoppingBasket> <LineItem> <Sale ItemType="Stock" NonDiscountableFlag="false" FixedPriceFlag="false"> <ItemID>ROC_SA_2</ItemID> <RegularSalesUnitPrice Currency="EUR">24.55000</RegularSalesUnitPrice> <Quantity Units="1" UnitOfMeasureCode="PCE">1</Quantity> <TaxIncludedInPriceFlag>false</TaxIncludedInPriceFlag> <NonPieceGoodFlag>false</NonPieceGoodFlag>

<FrequentShopperPointsEligibilityFlag>true</FrequentShopperPointsEligibilityFlag> <PriceTypeCode>00</PriceTypeCode> <NotConsideredByPriceEngineFlag>false</NotConsideredByPriceEngineFlag> </Sale> <SequenceNumber>55</SequenceNumber> <MerchandiseHierarchy ID="1">RF16231</MerchandiseHierarchy> </LineItem> <LineItem> <Sale ItemType="Stock" NonDiscountableFlag="false" FixedPriceFlag="false"> <ItemID>ROC_SA_1</ItemID> <RegularSalesUnitPrice Currency="EUR">25.21008</RegularSalesUnitPrice>

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 41

<Quantity Units="1" UnitOfMeasureCode="CT">1</Quantity> <TaxIncludedInPriceFlag>false</TaxIncludedInPriceFlag> <NonPieceGoodFlag>false</NonPieceGoodFlag>

<FrequentShopperPointsEligibilityFlag>true</FrequentShopperPointsEligibilityFlag> <PriceTypeCode>00</PriceTypeCode> <NotConsideredByPriceEngineFlag>false</NotConsideredByPriceEngineFlag> </Sale> <SequenceNumber>1</SequenceNumber> <MerchandiseHierarchy ID="1">RF16231</MerchandiseHierarchy> </LineItem> </ShoppingBasket> </PriceCalculateBody></PriceCalculateResponse>

Code Block 7 Error code (GKR-100500) in response, line 9

8.1 Error message format

The business errors are returned in the following format.

<error number> - <narrative> [LineItem(<SequenceNumber of the current line item>). ][Element<name of the current element>(<number of the current element>). ][Sent: <sent content>.[Expected: <expected content>.]]

8.2 Business Error Codes

The following table contains all possible error scenarios and the Business Error Codes and containedinformation defined for them. The table also contains the relating error codes from the PromotionCalculation Engine.

Errornumber Narrative

LineIteminfoavailable?

Specific handling regarding to theelement name Sent content Expected content

GKR-100502

Too manydecimalplaces.

xThe number of decimalplaces of the content ofthe element.

The maximum count ofdecimal places.

GKR-100500

Value notsupported. x The content of the

element. Enum where possible.

SDK Promotion Calculation Engine42 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Errornumber Narrative

LineIteminfoavailable?

Specific handling regarding to theelement name Sent content Expected content

GKR-100501 Value too big. x The length of the

content of the element. The maximum length.

GKR-100504

Structurewrong.

Dependson wherethe erroroccurs.

The content of theelement. Not available.

GKR-100505

ID notunique. x The content of the

element. Not available.

GKR-100507

Too manyQuantityelements.

x not availableThe number of Quantityelements in the lineitem.

"1"

GKR-100506

Missingelement orattribute.

x "Coupon" "none" "PrimaryLabel element"

x "Quantity" "none" "UnitOfMeasureCodeattribute"

x "Coupon" "none" "RewardType element"

x "Coupon" "none" "RewardVaue element"

- "ARTSHeader" "none" "MessageID element"

x "RetailPriceModifier" "none" "Quantity element"

x "PriceDerivationRuleEligibility" "none" "ReferenceID element"

x "PriceDerivationRuleEligibility" "none" "ReferenceSequenceNumberelement"

x "ExternalAction" "none" "ID attribute"

x "ExternalActionText" "none" "element itself"

x "ExternalActionText" "none" "ID attribute"

x "ExternalActionParameter" "none" "element itself"

x "ExternalActionParameter" "none" "ID attribute"

x "FrequentShopperPointsModifier" "none" "AppliedQuantity element"

GKR-100508

Not existingor unknown. - Not available. The content of the

element. Not available.

GKR-100503

Valuenegative. x The content of the

element. Not available.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 43

Errornumber Narrative

LineIteminfoavailable?

Specific handling regarding to theelement name Sent content Expected content

GKR-100509

Line item notallowed inline itemcalculationmode.

x "Coupon" Not available. Not available.

GKR-100510

Externalbenefit notallowed inline itemcalculationmode.

x "SystemOriginatorFlag =true"

"SystemOriginatorFlag = falseor missing"

SDK Promotion Calculation Engine44 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

9 PCE API interfaces

The following table lists all Pricing Engine interfaces with a brief description:

Package Interface Description

com.gk_software.pricing_engine PricingEngine The main interface representingpricing engine.

com.gk_software.pricing_engine.api.bucket Bucket Bucket for normalized calculation.

NormalizedItem Interface to represent a Bucketnormalized item.

com.gk_software.pricing_engine.api.calculator_service CalculatorService Service for calculating, distributing,and validating promotions.

TransactionCalculationService Service to perform transaction-related calculations.

com.gk_software.pricing_engine.api.context ContextThe PCE Context stores all requireddata for the processing of the PricingEngine.

ContextProviderInterface for accessing the Context inpreparation of multi-threading andPOS Mode.

ContextProviderFactory Factory for create a ContextProvider.

TxSummaryItem Summing the quantity and amount ofthe for a item.

com.gk_software.pricing_engine.api.data_access DataAccessService Data access service interface (DAL).

com.gk_software.pricing_engine.api.eligibility_service EligibilityService Eligibility-related operations service.

com.gk_software.pricing_engine.api.filter Filter

com.gk_software.pricing_engine.api.key CacheKey Composed key.

com.gk_software.pricing_engine.api.price_modification PriceModification Price modification methods interface.

com.gk_software.pricing_engine.api.price_modification PriceModificationFacade Price modification facade.

com.gk_software.pricing_engine.api.result ITransactionSummaryResult Save summary result on transactionlevel.

PartialResult Partial result for position ortransaction calculation.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 45

Package Interface Description

PartialResultBase Partial result base interface.

SummaryResult Summary result interface for position(line item) or transaction calculation.

com.gk_software.pricing_engine.api.rule_type CalculationRule Interface for calculation ruleoperations.

RuleFacade Facade interface for promotioncondition specific behaviors.

com.gk_software.pricing_engine.api.transaction TransactionDomainObjectService Service for handling transaction DOentities.

TransactionUpdateHandler Transaction update handler. Updatestransaction with calculated data.

com.gk_software.pricing_engine.api ConditionLoader Loads the conditions and stores theresult to the PCE Context.

EligibilityLoader Loads the eligibilities and stores theresult to the PCE context.

PricingEngineFactory Factory to instance PCE, PCE request,and configuration.

PricingEngineObjectFactoryContains factory methods forcalculation-related PricingEngineobjects.

PricingEngineRequest Pricing Engine request object.

PricingEngineResponse Pricing engine response object.

PromotionCalculator Promotion calculator.

ResolutionComparator Resolution comparator.

TransactionAnalyzer Analyzes transaction data and storesthe result to the PCE Context.

SDK Promotion Calculation Engine46 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

10 PCE models

The following table lists all Pricing Engine model interfaces with a brief description.

This is a high level overview. For details on the model, please refer to the Javadoc of the PCE model project.

10.1 Promotion Master Data

The promotion master data model is used for loading promotion data from the data access layer. It containsthe rules and configurations for calculation of promotions and prices.

Package Class Description

com.gk_software.pricing_engine.model.md.promotion

CombinationPromotionConditionEligibilitySO Combination of eligibilities.

CouponPromotionConditionEligibilitySO

Eligibility for coupon. If thePromotion.Condition.Eligibility.Coupon.IDList containsmore coupon IDs, one eligibility is created for each ID andthe eligibilities are connected via a combination eligibilityof the type OR.

CustomerGroupPromotionConditionEligibilitySO Eligibility for customer group.

CustomerPromotionConditionEligibilitySO Eligibility for customers.

ExternalActionParameterSOContains information about parameters for the action tobe performed by the client which invoked the pricingengine in case that the price derivation rule applies.

ExternalActionPromotionConditionRuleSO

An action is to be performed by the client which invokedthe pricing engine in case that the price derivation ruleapplies.

ExternalActionTextSOContains information about texts for the action to beperformed by the client which invoked the pricing enginein case that the price derivation rule applies.

ExternalTriggerValuePromotionConditionEligibilitySO Eligibility for external trigger.

Get3Pay2PromotionConditionRuleSO Rule: Get 3 Pay 2

IPromotionSOFactory Factory for all elements of the Domain Object Promotion.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 47

Package Class Description

ItemPromotionConditionEligibilitySO Item eligibility.

ManualPromotionConditionEligibilitySO Manual eligibility promotion condition.

MarketBasketAmountEligibilitySO Eligibility for market basket amount.

MatchingItemRelationSO Promotional items.

MatchingItemSO Matching item.

MatchingMhgRelationSO Promotional merchandise groups.

MerchandiseSetPromotionConditionEligibilitySO

Defines a merchandise set resulting from the applicationof set operations to merchandise hierarchy groups and/oritems and the further conditions regarding to quantitiesand amounts which govern the application of theassociate rule to an item falling under the resultingmerchandise set at the time an instance of the item isrecorded as a line item in a sale/return.

MerchandiseSetRelationSO An association between two merchandise sets thatestablishes one as the higher and one as the lower level.

MerchandiseSetSO A merchandise set (that is, the reference to the rootelement of the merchandise set).

MHGPromotionConditionEligibilitySO

Merchandise hierarchy group eligibility.

Eligibilities fromPromotion.Condition.Eligibility.MerchandiseHierarchyGroupList|MerchandiseHierarchyGroup. Eligibilities fromPromotion.Condition.Eligibility.ItemList|Item in case theeligibility contains more then one item.

Additionally, if thePromotion.Condition.Eligibility.MerchandiseHierarchyGroup element contains IntersectionList, one MHG eligibility iscreated for each IntersectionList.ID and the MHGeligibilities are connected via a CombinationEligibility ofthe type Intersection.

MixAndMatchPromotionConditionRuleSO Mix and Match.

PositionTypePromotionConditionEligibilitySO Eligibility for position type.

PromotionConditionEligibilitySO Promotion condition eligibility.

PromotionConditionRuleSO Promotion condition rule.

PromotionConditionSO Condition of the promotion.

SDK Promotion Calculation Engine48 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Package Class Description

PromotionConditionTimeGroupSO Time restriction.

PromotionMhgFilterSO This domain object contains the promotion data relevantfor the PCE.

PromotionSO This domain object contains the promotion data relevantfor the PCE.

PromotionTextSO Language-dependent texts to a promotion.

RebatePromotionConditionRuleSO Simple discount.

ThresholdPromotionConditionEligibility Threshold promotion condition data for eligibility.

WorkerDiscountGroupPromotionConditionEligibilitySO Eligibility for workers.

10.2 Transaction

The transaction data model is the data model for the client data. It is mapped from the incoming request andthe results are mapped back.

Package Class Description

com.gk_software.pricing_engine.model.transaction FrequentShopperPointsModifier A line item modifier that reflects a

modification of the frequent shopper points.

ITransactionFactory Factory for all elements of the Domain ObjectTransaction.

LoyaltyRewardLineItem

A RetailTransactionLineItem sub-type thatrecords the crediting of aCustomerLoyaltyAccount with points, or thegifting of an Item or GiftCertificate to thataccount because of some Promotion. In thePCE context, at the moment, we are usingpoints only.

ManualPromotionTrigger Common interface for manual promotiontriggers.

PriceModificationLineItem

A line item component of a RetailTransactionthat records the granting of a reduction orincrease of price on all Items in theTransaction.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 49

Package Class Description

RetailPriceModifier

A line item modifier that reflects amodification of the retail selling price. It isprovided by PLU through the application of apredefined price change rule that dependson parameters provided during the saletransaction. This entity is intended to supportpricing schemes which vary depending on thenumber of items purchased like 2 for 1 sales,buy 2 get the 3rd one free, etc. The pricechange reflected in this modifier may betreated as a markdown, a discount, apromotional expense, etc. Accordingly, itrepresents a merging of the formerDISCOUNT MODIFIER, ALLOWANCE MODIFIERand PRICE LOOKUP EXCEPTION MODIFIERentity types. This entity is also intended tosupport tiered pricing that is determined by ashopper/customer affiliation with somegroup like AARP etc. that receives specialprice breaks.

RetailTransaction

A type of Transaction that records thebusiness conducted between the retailenterprise and another party involving theexchange in ownership and/or accountabilityfor merchandise and/or tender or involvingthe exchange of tender for services.

RetailTransactionCouponSummary Information about coupons which wereapplied for that sales transaction.

RetailTransactionCustomer Information about the customer thetransaction was created for.

RetailTransactionCustomerGroupAssignment

The customer groups which are assigned tothe transaction (indirectly by the assignedcustomers).

RetailTransactionExternalTrigger

Contains the external values which wererequested via web services in order to checkwhether the transaction is eligible forpromotions containing eligibilities of type"external trigger value".

RetailTransactionLineItem

A detail line item of a RetailTransaction thatrecords the business conducted between theretail store and another party involving theexchange in ownership and/or accountabilityfor merchandise and/or tender or involvingthe exchange of tender for services.

SDK Promotion Calculation Engine50 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Package Class Description

RetailTransactionLineItemAssociation

Associative entity recording relationshipsbetween line items within the sameRetailTransaction.

Examples of usage of this entity include:

· Associating an original sales lineitem to a return line item.

· Associating an original sales lineitem to an exchange line item.

· Associating a sales line item to afee line item.

RetailTransactionModifierCoupon Information about coupons which wereapplied for that line item.

RetailTransactionPromotionExternalActionParameter

Contains information about the parametersof the action to be performed by the clientwhich invoked the pricing engine in case thatthe price derivation rule applies.

RetailTransactionPromotionExternalActionText

Contains information about the texts of theaction to be performed by the client whichinvoked the pricing engine in case that theprice derivation rule applies..

RetailTransactionPromotionPriceDerivationRule

Contains relevant data regarding to the pricederivation rules which apply to thetransaction resp. its line items.

RetailTransactionPromotionTriggerManual triggers which are created by POSfunction and used as eligibilities forconditions.

RetailTransactionTotal

A monetary or unit count total for theRetailTransaction. UsuallyTotalTaxableAmount, TotalTaxCollected,TotalAmountPaid, TotalItemCount, etc...

ReturnLineItem

A sub-type of SaleReturnLineItem recordingthe reason and disposal of an Item beingreturned by a Customer. If the return is to berecorded against the original retailtransaction line item, this should be recordedas a RetailTransactionLineItemAssociationwithRetailTransactionLineItemAssociation.AssocationTypeCode of "return".

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 51

Package Class Description

SaleReturnLineItem

A line item component of a RetailTransactionthat records the exchange in ownership of amerchandise item (that is, a sale or return) orthe sale or refund related to a service. TheSale or refund related to a service capturesan item and action taken that reflects anevent of interest to the retail business butDOES NOT RESULT in the exchange inownership of a merchandise item.

SaleReturnLineItemMerchandiseHierarchyGroup

All merchandise hierarchy groups which aredirectly assigned to the item.

SaleReturnLineItemModifierCoupon Information about coupons which wereapplied for that line item.

SaleReturnLineItemModifierReference

Contains all line items of the currenttransaction which together caused that aprice derivation rule was applied (if the pricederivation rule was applied more than onetime summarization takes place); is filledonly in case that several positions togethercaused it, is needed for calculating theaverage rebate in case of item return.

SaleReturnLineItemPromotionTriggerManual triggers which are created by POSfunction and used as eligibilities forconditions.

SaleReturnLineItemSalesOrder Information about the SAP customer orderrelated to this line item.

Transaction

A record of business activity that involves afinancial and/or merchandise unit exchangeor the granting of access to conduct businessat a specific device, at a specific point in timefor a specific employee.

TransactionCategory Describes which categories transactions fallinto.

SDK Promotion Calculation Engine52 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

11 Configuration

11.1 PromotionServiceConfig

11.1.1 Configuration as input parameter

It is possible to hand over the configuration described below as an input parameter object to the PCE whencalling it. When doing so, only changed configuration parameters must be handed over.

The precedence is:

11.1.2 Configuration by configuration file(s) available at service site

In case the configuration is not handed over to the PCE when calling it, the configuration is determinedbased on configuration files available at service site:

It will be checked whether a default configuration file exists. This file is used as fallback in case no moregranular configuration information is available.

NotethatanyparametersupportingalistofvaluesisoftypeStringwithseparatorcharactersemicolon(;).

Parameter Name Data type, Range Description Default

pointsFactor Double

This is the factor „percentual“points (basis points as well asmultiple points) have to bemultiplied with (in contrast tothis, fix points are notmultiplied with this factor).

1.0

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 53

Parameter Name Data type, Range Description Default

transactionRebateMethod

· Total

· Trigger

Specifies how to determinethe calculation base of thereceipt related discount:

· Total = Receipt total

· Trigger = Via triggers

Trigger

timeValidationMethod

· Promotion

· Eligibilities

Method to determine thevalidity level of a condition:

· Promotion

· Eligibilities

Promotion

priceTypeCodesWithoutDiscounts string

List of price types generallynot considered by the LoyaltyServer (real, manually enteredprices).

List of codes for price types ofitems excluded in calculation.Possible values:

"00" : = regular price

"01" : = current/reduced price

(evaluated againstItem.getPriceTypeCode())

null

itemTypesWithoutReceiptRelatedDiscounts string

List of line item types whichare not allowed for receiptrelated monetary discounts(list of codes).

SO

itemTypesWithoutReceiptRelatedPoints string

List of line item types whichare not allowed for receiptrelated bonus points discount(list of codes).

SO

itemTypesWithoutPoints stringList of line item types generallynot considered for bonus pointcalculation (list of codes).

SDK Promotion Calculation Engine54 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Parameter Name Data type, Range Description Default

itemTypesWithoutDiscounts string

List of line item types generallyexcluded from discount (list ofcodes).

Supported Types with codes:

· common sale returnline item: CO

· deposit line item: DI

· down payment lineitem: DP

· downpaymentclearing line item: DC

· empties return lineitem: ER

· gift certificate lineitem: GC

· invoice payment lineitem: IP

· item information lineitem: II

· pay in line item: PI

· pay out line item: PO

· prepaid line item: PR

· promotion giftcertificate line item:PG

· sales order line item:SO

· sales order pickupline item: PU

· scale receipt lineitem: SC

nonPieceItemPerPosition Boolean

Specifies whether the percentrebate for non-piece itemsshould be calculated perposition ('true') or per item unit('false'). (Default is 'false').

False

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 55

Parameter Name Data type, Range Description Default

discountVectorForItemEligibilities Boolean

Specifies whether the discountcontrol vector check is usedfor conditions with itemeligibilities. (Default is 'false').

False

userActionProhibited BooleanSpecifies whether it isforbidden that the user selectsor enters a condition value.

False

discountVectorMethod

· Common

· All

Defines which positions arechecked against the discountvector:

· Common = only for'item' type positions(default)/ item lines

· All = for all positiontypes/ all line itemtypes that areallowed for amonetary discount ora bonus pointcalculation

Common

calculationTimeLimit LongDefines the time limit in ms forthe best price algorithm(server.collision.method=3).

1000

rebateShareRoundingMethod

· Down

· Up

· Commercial

Defines the rounding methodfor rebate shares (not used forpoints):

· Commercial =standard (half up)/commercial rounding

· Down = Truncate

· Up = Round up

Commercial

SDK Promotion Calculation Engine56 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Parameter Name Data type, Range Description Default

pointsShareRoundingMethod

· Down

· Up

· Commercial

Defines the rounding methodfor points shares:

· Commercial =standard (half up)/commercial rounding

· Down = Truncate

· Up = Round up

Commercial

rebateShareRoundingDestinationValue Integer

Defines the roundingdestination value for rebateshares, which are used toround the value to the properdenomination (not used forpoints).

Example: decimal places = 2,destination value = 5 -> thevalue will be rounded to 0.05denomination. (Default is 1)

Additional roundinginformation:

· 1 = There is nofurther handling ofthe rounding result.

· 5 = The roundingresult is adjusted tocorrespond to thepreceding orsubsequent multipleof 5.

1

pointsRating Double Defines the rating to calculatemoney equivalent of points. 0.01

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 57

Parameter Name Data type, Range Description Default

itemChooseMethod

· Lowest

· Highest

· LowestPerInterval

· HighestPerInterval

Defines the order in whichbenefits apply to items:

· Lowest = take firstitems with lowestprice (lowest benefitfirst)

· Highest = take firstitems with highestprice (highest benefitfirst)

· LowestPerInterval =lowest benefit perinterval first

· HighestPerInterval =highest benefit perinterval first

Lowest

rebateShareDecimalPlacesCount Integer (0 - 4)

Defines the number ofdecimal places (0 - 4) forrebate splitting.

Possible values: 0 - 4

2

pointsShareDecimalPlacesCount Integer (0-4)

Defines the number ofdecimal places (0 - 4) forpoints splitting.

Possible values: 0 - 4

0

percentualPointsMethod

· After

· Before

Defines the method which isused to calculate percentualpoints condition values:

· After = round at theend of calculation forquantity unit

· Before = roundbefore multiplicationbyREDUCTION_PERCENT

Before

SDK Promotion Calculation Engine58 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Parameter Name Data type, Range Description Default

rebateShareMethod

· Standard

· Share

Defines the method forproportionally distributing thereceipt discount among thedifferent receipt line items (forreceipt related monetarydiscounts, not used forpoints):

· Standard = standardcalculation, positionssorted in order asthey were registered

· Share = shares forpercent rebates arecalculated directlyfrom position price,positions are sortedaccording to theirprices, starting withthe smallest lineitem amount.

Share

enabled Boolean

Defines the enabled flag.

If false, no calculation ofpromotions is executed.

True

conditionLimit Long

Defines limits which are usedfor the condition calculation.In addition, the maximumcount of active conditions witha common sequence andresolution which have to becomputed.

100

allowZeroRebate BooleanDecides whether conditionswhich provide a zero rebatewill be used.

False

checkApiVersion Boolean

If true, it enables validation ofthe API Major and Minorversion send in the requestheader.

false

defaultBusinessUnitGroupId Long

Id of default business Unitgroup id, if it could not be readfrom request (GK integrationonly).

100000000000000014

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 59

Parameter Name Data type, Range Description Default

calculationMode

· Basket

· LineItem

Either Basket or LineItem todetermine defaultcalculationMode if not set inrequest.

Basket

saleReturnTypeCodesForSales

· 00

· 01

· 02

Defines thesaleReturnTypeCodes used forsalestype line items. Used foreligibility queries to dataaccess layer. Use coded value(0X) corresponding to:

· 00: SALES_RETURNS

· 01: SALES

· 02: RETURNS

· SALES

· SALES_RETURNS

saleReturnTypeCodesForReturns

· 00

· 01

· 02

Defines thesaleReturnTypeCodes used forreturn type line items. Used foreligibility queries to dataaccess layer. Use coded value(0X) corresponding to:

· 00: SALES_RETURNS

· 01: SALES

· 02: RETURNS

· RETURNS

· SALES_RETURNS

SDK Promotion Calculation Engine60 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

12 Libraries

The following external open source libraries are dependencies of the Promotion Calculation Engine.

All are available via Maven central.

ThedefinedversionsofthelibrariesaretheonesthatthePromotionCalculationEngineisbuiltandtestedagainst.

AnewerversionofalibrarymayworkifthethirdpartyproviderdidnotchangedtheirAPIinanincompatibleway.

Group ID Artifact Id Version Scope Description

org.springframework spring-beans3.0.7,4.1.9 or4.3.3

compile&runtime

Spring framework.

org.springframework spring-core3.0.7,4.1.9 or4.3.3

compile&runtime

Spring framework.

org.springframework spring-expression

3.0.7,4.1.9 or4.3.3

compile&runtime

Spring framework.

org.springframework spring-context

3.0.7,4.1.9 or4.3.3

compile&runtime

Spring framework.

org.slf4j slf4j-api 1.7.21compile&runtime

Logging API.

com.fasterxml.jackson.core jackson-annotations 2.6.4

compile&runtime

XML & JSON Parsing.

com.fasterxml.jackson.core jackson-databind 2.6.4

compile&runtime

XML & JSON Parsing.

com.fasterxml.jackson.core jackson-core 2.6.4compile&runtime

XML & JSON Parsing.

joda-time joda-time 2.6compile&runtime

Datetime utilities.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 61

Group ID Artifact Id Version Scope Description

com.google.guava guava 12.0compile&runtime

Guava is a set of core libraries that includes new collectiontypes (such as multimap and multiset), immutable collections,a graph library, functional types, an in-memory cache, andAPIs/utilities for concurrency, I/O, hashing, primitives,reflection, string processing, and much more!

net.jperf jperf 1.0.3compile&runtime

Performance Monitoring and Statistics for Java Code.

commons-collections commons-collections 3.2.2

compile&runtime

Apache commons collection helper utilities.

Extends or augments the Java Collections Framework.

commons-lang commons-lang 2.6

compile&runtime

Apache commons utilities.

Provides extra functionality for classes in java.lang.

com.google.code.findbugs annotations 3.0.1 compile Findbugs static code check annotation. Compile time onlydependency.

junit junit 4.12 test Junit testing framework.

org.mockito mockito-all 1.10.19 test Mocking framework for unit tests.

org.springframework spring-test3.0.7,4.1.9 or4.3.3

test Spring testing framework.

org.meanbean meanbean 2.0.3 test Testing framework for Java beans.

SDK Promotion Calculation Engine62 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

13 Performance Logging

13.1 Overview

The PCE core includes some basic performance monitoring features.

The monitoring is based on the JPerf Open Source library. This allows a fine-grained performance loggingwith some advanced analysis capabilities. The monitoring is controlled via logger settings.

There are different measurement points with additional new loggers that allow controlling the detail of theoutput.

13.2 Usage

To enable the performance logging, set the corresponding logger log level to INFO, DEBUG or TRACE leveland log the information to a specific performance.log file.

There are different loggers available, see below for details.

The performance.log contains log entries in the following format (depending on your log-formatconfiguration).

INFO[main]:start[1494336965104]time[171]tag[pricing.service.calculate.success]message[MessageId:cha_basic_not_discountable_flag1_request]

Explanation:

INFO: Log level at which the message is logged.

[main]: Thread name where the log is created.

start[1494336965104] : Timestamp (System.currentTimeMillis) at which the log was produced.

time[171] : This is the time in ms that was measured for the operation.

tag[pricing.service.calculate.success] : The tag is a formalized definition of the operation that is measured.For details on the available tags, see below.

message[MessageId: cha_basic_not_discountable_flag1_request] : Some log entries have an optionalmessage that gives some more details on the measurement (that is, messageId of the request).

For example:

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 63

DEBUG [http-nio-9081-exec-1]: start[1494517222819] time[12]tag[pricing.engine.internal.execute.prepareContext]DEBUG [http-nio-9081-exec-1]: start[1494517222832] time[1]tag[pricing.engine.internal.execute.clearPromotionDataFromTransaction]DEBUG [http-nio-9081-exec-1]: start[1494517222834] time[18]tag[pricing.engine.internal.execute.executeTransactionAnalyzer]TRACE [http-nio-9081-exec-1]: start[1494517222853] time[184]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]TRACE [http-nio-9081-exec-1]: start[1494517223039] time[40]tag[pricing.data_access.DataAccessServiceDelegate.getMarketBasketAmountEligibilities]DEBUG [http-nio-9081-exec-1]: start[1494517222852] time[227]tag[pricing.engine.internal.execute.executeEligibilityLoader]INFO [http-nio-9081-exec-1]: start[1494517222819] time[262] tag[pricing.engine.process]INFO [http-nio-9081-exec-1]: start[1494517222723] time[362]tag[pricing.service.calculate.success] message[MessageId:i_can_calculate_large_baskets_1_request]DEBUG [http-nio-9081-exec-2]: start[1494517223292] time[5]tag[pricing.engine.internal.execute.executeTransactionAnalyzer]TRACE [http-nio-9081-exec-2]: start[1494517223299] time[5]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]TRACE [http-nio-9081-exec-2]: start[1494517223304] time[4]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]TRACE [http-nio-9081-exec-2]: start[1494517223309] time[3]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]TRACE [http-nio-9081-exec-2]: start[1494517223312] time[3]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]TRACE [http-nio-9081-exec-2]: start[1494517223316] time[2]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]TRACE [http-nio-9081-exec-2]: start[1494517223319] time[6]tag[pricing.data_access.DataAccessServiceDelegate.getMarketBasketAmountEligibilities]DEBUG [http-nio-9081-exec-2]: start[1494517223299] time[26]tag[pricing.engine.internal.execute.executeEligibilityLoader]INFO [http-nio-9081-exec-2]: start[1494517223292] time[34] tag[pricing.engine.process]INFO [http-nio-9081-exec-2]: start[1494517223283] time[46]tag[pricing.service.calculate.success] message[MessageId:i_can_calculate_large_baskets_5_request]DEBUG [http-nio-9081-exec-3]: start[1494517223390] time[45]tag[pricing.engine.internal.execute.executeTransactionAnalyzer]TRACE [http-nio-9081-exec-3]: start[1494517223436] time[5]tag[pricing.data_access.DataAccessServiceDelegate.getItemEligibilities]

Forperformancelogging,youshouldcreateanewlogappenderthatlogsallloggersstartingwithperformance.pricing-engine,

thatis,forlogback:

<logger name="performance.pricing-engine" level="info" additivity="false">

<appender-ref ref="PERF" />

</logger>

SDK Promotion Calculation Engine64 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Recommendedlogformatterpatternforlog4j:

<param name="conversionPattern" value="%-5p [%t]: %m%n"/>

Recommendedlogformatterpatternforlogback:

<layout>

<pattern>%-5level [%thread]: %message%n</pattern>

</layout>

13.2.1 Measurement Points

All measurements are using a logger depending on the module and classname.

The logger name pattern used is: performance.<ModuleName>.<ClassName>,

for example: performance.engine.com.gk_software.pricing_engine.engine.PricingEngineImpl

Depending on the log level set for the different loggers, there may be additional more detailed performancelog entries measured. The overhead of the performance logging is very low (<1% overhead), but it isrecommended to use the DEBUG and TRACE level only if you need some more detailed information, as it willadd a lot more data to the performance log.

Alloperationsthataremeasuredwithlessthan1msarenotwrittentotheperformancelog.

Module Class name Log Level Tag Description

psi-sap

com.gk_software.pricing_engine.psi.service.PromotionPricingServiceImpl

INFOpricing.service.calculate.success

pricing.service.calculate.error

Overall processingtime of a PCE servicecall.Error and successtags used dependingon result(BusinessError orSuccess).

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 65

Module Class name Log Level Tag Description

engine com.gk_software.pricing_engine.engine.PricingEngineImpl INFO pricing.engine.process

Overall processingtime of thepromotioncalculation(excluding requestand responseparsing).

DEBUG pricing.engine.internal.execute.prepareContext Time to initializeengine.

DEBUG pricing.engine.internal.execute.clearPromotionDataFromTransaction

Time to clearprevious promotiondata fromtransaction.

DEBUG pricing.engine.internal.execute.executeTransactionAnalyzer

Time to parse andanalyze thetransaction data.

DEBUG pricing.engine.internal.execute.executeEligibilityLoader

Overall time to loadall relevanteligibilities, check,and activate them.

DEBUG pricing.engine.internal.execute.executeConditionLoader

Time to load allconditions and rulesfor active eligibilities.

DEBUG pricing.engine.internal.execute.executeConditionCalculator

Time to do thepromotioncalculation for allviable promotions.

DEBUG pricing.engine.internal.execute.transactionUpdateHandler>

Time to updatetransaction datawith calculationresults.

engine com.gk_software.pricing_engine.engine.PromotionCalculatorImpl DEBUG pricing.calculation.calculateLineItemsConditions

Time to calculate allPosition (LineItem)related promotions.

DEBUG pricing.calculation.calculateTransactionConditions

Time to calculate allTransaction (Basket)related promotions.

data_access

com.gk_software.pricing_engine.api.data_access.DataAccessServiceDelegate

TRACE pricing.data_access.DataAccessServiceDelegate.getEligibility

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

SDK Promotion Calculation Engine66 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Module Class name Log Level Tag Description

TRACE pricing.data_access.DataAccessServiceDelegate.getChildEligibilitiesCount

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getItemEligibilities

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getCustomerGroupEligibilities

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getCouponEligibilities

Detailed logging ofsingle data accessmethod for loadingdata from DB.

TRACE pricing.data_access.DataAccessServiceDelegate.getMerchandiseGroupEligibilities

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getMerchandiseSetEligibilities

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getCombinationEligibility

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getMarketBasketAmountEligibilities

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getParentEligibilitiesForMerchandiseGroup

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 67

Module Class name Log Level Tag Description

TRACEpricing.data_access.DataAccessServiceDelegate.getChildEligibilitiesForParentEligibilitiesForMerchandiseGroup

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACEpricing.data_access.DataAccessServiceDelegate.getParentCombinationEligibilitiesForMerchandiseGroup

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getPromotion

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getPromotionConditions

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getItemRule

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getGet3Pay2Rule

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.findAssociatedMhgByChildId

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getMixAndMatchRule

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getExternalActionRule

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

SDK Promotion Calculation Engine68 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

Module Class name Log Level Tag Description

TRACE pricing.data_access.DataAccessServiceDelegate.getMixAndMatchItems

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.findRoundingRuleByKey

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getManualPromotionEligibilities

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

TRACE pricing.data_access.DataAccessServiceDelegate.getRule

Detailed logging ofsingle data accessmethod for loadingpromotion data fromDB.

13.2.2 Analysis of Performance logs

The JPerf library has some built-in log parser to ease the evaluation of the performance logs.

Use it on the command line like follows (having the jperf-1.0.3.jar downloaded or got from webapp/libfolder):

java -jar jperf-1.0.3.jar log/performance.log -o log/performance-summary.log <options>

Calling this script creates a new performance-summary.log file that summarizes the execution times of themeasured data and generates statistical information.

An example is shown in the following section:

Performance Statistics 2017-05-09 15:36:00 - 2017-05-09 15:36:30Tag Avg(ms)Min Max Std-Dev Count Totalpricing.calculation.calculateLineItemsConditions 204,09 582 229,0 8 1632

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 69

pricing.calculation.calculateTransactionConditions 14,014 14 0,0 1 14pricing.data_access.DataAccessServiceDelegate.getChildEligibilitiesCount 2,51 6 2,1 4 10pricing.data_access.DataAccessServiceDelegate.getCombinationEligibility 3,83 6 1,3 4 15pricing.data_access.DataAccessServiceDelegate.getCouponEligibilities 2,32 3 0,5 7 16pricing.data_access.DataAccessServiceDelegate.getCustomerGroupEligibilities 1,71 3 0,7 18 31pricing.data_access.DataAccessServiceDelegate.getExternalActionRule 5,03 7 2,0 2 10pricing.data_access.DataAccessServiceDelegate.getItemEligibilities 3,31 52 4,2 155 519pricing.data_access.DataAccessServiceDelegate.getItemRule 1,81 6 1,3 12 22pricing.data_access.DataAccessServiceDelegate.getManualPromotionEligibilities 2,61 7 1,3 14 36pricing.data_access.DataAccessServiceDelegate.getMarketBasketAmountEligibilities 3,92 24 3,9 32 126pricing.data_access.DataAccessServiceDelegate.getMerchandiseGroupEligibilities 2,01 4 0,9 24 49pricing.data_access.DataAccessServiceDelegate.getMixAndMatchItems 5,05 5 0,0 1 5pricing.data_access.DataAccessServiceDelegate.getMixAndMatchRule 7,07 7 0,0 1 7pricing.data_access.DataAccessServiceDelegate.getPromotion 3,81 22 4,9 15 57pricing.data_access.DataAccessServiceDelegate.getPromotionConditions 10,13 50 10,0 18 181pricing.engine.internal.execute.executeConditionCalculator 183,69 582 223,9 9 1652pricing.engine.internal.execute.executeConditionLoader 26,44 88 23,6 12 317pricing.engine.internal.execute.executeEligibilityLoader 34,75 341 59,7 32 1111pricing.engine.internal.execute.executeTransactionAnalyzer 8,23 66 11,2 32 261pricing.engine.internal.execute.prepareContext 6,06 6 0,0 1 6pricing.engine.internal.execute.transactionUpdateHandler 114,34 460 180,4 9 1029pricing.engine.process 148,010 1089 270,4 30 4441pricing.service.calculate.error 9,85 18 4,2 6 59pricing.service.calculate.success 182,516 1098 290,7 30 5474Performance Statistics 2017-05-09 15:36:30 - 2017-05-09 15:37:00Tag Avg(ms)Min Max Std-Dev Count Totalpricing.calculation.calculateLineItemsConditions 124,716 557 193,9 6 748pricing.calculation.calculateTransactionConditions 5151,8

SDK Promotion Calculation Engine70 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

52 25534 10191,1 5 25759pricing.data_access.DataAccessServiceDelegate.getChildEligibilitiesCount 2,01 3 0,7 4 8pricing.data_access.DataAccessServiceDelegate.getCombinationEligibility 3,53 4 0,5 4 14pricing.data_access.DataAccessServiceDelegate.getExternalActionRule 2,72 3 0,5 3 8pricing.data_access.DataAccessServiceDelegate.getItemEligibilities 2,92 9 1,7 16 47pricing.data_access.DataAccessServiceDelegate.getItemRule 1,41 3 0,6 14 20pricing.data_access.DataAccessServiceDelegate.getMarketBasketAmountEligibilities 4,22 17 4,4 11 46pricing.data_access.DataAccessServiceDelegate.getMerchandiseGroupEligibilities 2,02 2 0,0 2 4pricing.data_access.DataAccessServiceDelegate.getPromotion 1,71 3 0,7 17 29pricing.data_access.DataAccessServiceDelegate.getPromotionConditions 6,65 10 1,5 17 112pricing.engine.internal.execute.executeConditionCalculator 2410,516 25535 7314,1 11 26515pricing.engine.internal.execute.executeConditionLoader 19,010 53 11,5 11 209pricing.engine.internal.execute.executeEligibilityLoader 17,08 37 9,5 11 187pricing.engine.internal.execute.executeTransactionAnalyzer 1530,93 16795 4826,9 11 16840pricing.engine.internal.execute.transactionUpdateHandler 130,17 511 147,6 10 1301pricing.engine.process 269,261 1105 291,3 10 2692pricing.service.calculate.success 279,169 1113 290,9 10 2791

For each operation, you get information on average execution time, minimum and maximum executiontimes, standard deviation, invocation count of the method, and total execution time of all calls.

The parser generates statistics for each 30 seconds time slice by default. This is configurable by passing theparameter -t (time in ms). By passing the -r parameter, you get additional statistical rollups that summarizetags with the same prefix.

There are the following additional options that can be used (use --help to print them out).

Arguments: logInputFile - The log file to be parsed. This is log/performance in the analyze-performance script. -o|--out|--output outputFile - The file where generated statistics should be written. Ifnot specified, statistics are written to stdout. This is fixed to log/performance-summary.log in the analyze-performance script -g|--graph graphingOutputFile - The file where generated perf graphs should be written. If

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 71

not specified, no graphs are written. -t|--timeslice timeslice - The length of time (in ms) of each timeslice for whichstatistics should be generated. Defaults to 30000 ms. -r - Whether or not statistics rollups should be generated. If not specified, rollups arenot generated. -f|--format text|csv - The format for the statistics output, either plain text or CSV.Defaults to text. If format is csv, then the columns output are tag, start, stop,mean, min, max, stddev, and count.Note that out, stdout, err and stderr can be used as aliases to the standard output streamswhen specifying output files.

You can also output the data in a graphical format or as CSV to import into Excel.

See the JPerf documentation for more details.

13.3 Development

As a developer of a PCE extension, you may want to add additional measurement points in your own code.

The basic class for measurement of execution times form JPerf library is LoggingStopWatch. Create aninstance of this class and use start, lap, and stop methods for trigger performance measurement. See alsoJPerf developer guide for more details.

The creation of a LoggingStopWatch object is very cheap, so it adds no performance overhead.

There is a helper class com.gk_software.pricing_engine.common.utils.PerformanceUtils in commons project tosupport you in doing so. This class contains several static methods to help you in using performancemeasurement.

The following code can be used to create and start a new stopWatch at the beginning of a method:

LoggingStopWatch logWatch = PerformanceUtils.start(PERF_LOGGER, PerformanceLevel.DEBUG, "pricing.engine.internal.execute", null);

You should create a new watch on each method call to be thread-safe. While this adds some Garbagecollector overhead, this is negligible compared to the business method execution.

The newStopWatch method automatically adds a threshold of 1 ms to the LoggingStopWatch, which meansmethods executing in less than 1ms are not logged. The PerformanceLevel defines on which log level themeasurement is logged.

You could also get a performance logger in your class and create stop watches from there:

SDK Promotion Calculation Engine72 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

private static final Logger PERF_LOGGER = PerformanceUtils.getPerfLog("engine",PricingEngineImpl.class);

....

LoggingStopWatch watch = PerformanceUtils.newStopWatch(PERF_LOGGER, PerformanceLevel.INFO);

Itisrecommendedtouseaseparateloggerforperformanceloggingtoalloweasyfilteringinthelogconfig.

When you create a new instance of a LoggingStopWatch, it is automatically initialized with current time, sothere is no need to start it. If you want to reset or restart it inside your code, use the start() or lap() methods.

To stop and log a watch, use the stop() method.

if(logWatch.isLogging()) { PerformanceUtils.lap(logWatch, "pricing.engine.internal.execute.prepareContext", null);}

PerformanceUtils.stop(logWatch, "pricing.engine.internal.execute.transactionUpdateHandler",null);

Use watch.isLogging() when you generate some more complex tags to prevent unnecessary overhead whenperformance monitoring is not enabled. You can pass the tag in start stop or lap method as you need,recommended is to pass it on stop. You may optionally use stop(String,String) to pass an additional message.

The tag should have several levels separated by a point (.), a similar syntax like a log4j logger name. It is usedfor grouping entries during the analysis. Best practice is to prefix the tag with some fixed entry based on themodule, class, and/or method measured and then some details if needed for granular measurement.

SDK Promotion Calculation EngineContent © 2016 SAP SE or an SAP affiliate company. All rights reserved. 73

14 Glossary

The glossary is intended to support understanding of the main terms used in this documentation.

Term Definition

ARTS The Association for of Retail Technology Standards (ARTS) is an organization providing application standardsand guidance to the retail industry.

Business Error Feedback regarding problems caused by the data sent in with the request. Currently, only errors caused bywrong or missing data in the request are supported.

Calculation Rule Describes the benefit to be granted to the customer in case that the condition is applied.

ConditionA condition can be understood as a single action granting a benefit to the customer. It consists of a set oftriggers (eligibilities), time validity, and a rule describing the benefit. Multiple conditions can belong to apromotion.

Context Holds the complete state for transaction processing and promotion calculation.

Domain (Object)Model Conceptual model of a problem or business domain.

Eligibility Precondition which has to be fulfilled in order to apply the condition. An eligibility triggers a condition.

Extension Map Possibility to define references to external data structures for the objects of a transaction.

Pricing Engine The core of the Promotion Calculation Engine. The Pricing Engine passes the request from the application,performs the price determination and returns the result.

Pricing ServiceInterface (PSI)

Standard interface schema provided by ARTS for integrating a pricing service with a price requesting orselling system.

Promotion Functional mapping of a campaign granting a benefit to the customer. A promotion consists of one or moreconditions.

Request

Message that contains common information pieces which are needed in order to process the message: Ashopping basket with multiple line items and other information being relevant for the calculation of thebenefits for the shopping basket.

The request is provided via the client API.

ResponseResponding message regarding to the request sent in. This can be the updated shopping basket includingcalculated discounts and bonus points as well as information about used promotion master data and appliedcoupons, or an error information in case that the request could not be processed.

Technical Error Error due to technical problems which prevents the calculation to be fulfilled (for example, a databaseexception).

Transaction The shopping basket with line item data and other information relevant for price calculation.

SDK Promotion Calculation Engine74 © 2016 SAP SE or an SAP affiliate company. All rights reserved. Content

www.sap.com/contactsap

© 2016 SAP SE or an SAP affiliate company. All rights reserved.No part of this publication may be reproduced or transmitted in any form or forany purpose without the express permission of SAP SE or an SAP affiliate company.SAP and other SAP products and services mentioned herein as well as theirrespective logos are trademarks or registered trademarks of SAP SE (or an SAPaffiliate company) in Germany and other countries. All other product and servicenames mentioned are the trademarks of their respective companies. Please seehttp://www. sap.com/corporate-en/legal/copyright/index.epx#trademark foradditional trademark information and notices.

Material Number: