Overview

The Loyalty Rule service is a core component of Loyalty. This service is used to create rules in the system as well as process appropriate rules when the end user makes an activity on the storefront. All the user activities such as Registration, Order, Redemption, Rating, Review, and Tier Upgrades are processed by the Loyalty Rule service.


API Reference

/rules

This resourceType defines the GET, POST, DELETE methods and their responses for a collection resource.

/rules

get

Gets all rules

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services
post

(Do not use) Creates a new rule for a Loyalty program. Use /saveRule for creating a new rule.

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services

/rules/aggr

get

Gets Average, Sum and Count aggregation for Rules

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services

/rules/{ruleId}

This resource type defines the GET, PUT, DELETE methods and their responses for a single element resource.

get

Gets a specific rule of a Loyalty program based on the rule id provided

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services
put

(Do not use) Updates a specific rule of a Loyalty program based on the rule id provided

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services
delete

Deletes a specific rule of a Loyalty program based on the rule id provided

Accepted scopes:

  • 'sap.loyengine_delete' - Perform delete operations on Loyalty Rule services

/saveRule

This resourceType defines the POST, PUT methods and their responses for a collection resource.

/saveRule

post

Creates a rule and generates a DRL file.Use this endpoint to create a new rule.

Details:

  • A DRL file is generated for rule saved from the rule builder UI
  • The DRL is stored as a base64 encoded content in the document repository

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services
put

Updates a rule and generates a DRL file. Use this endpoint to update an existing rule.

Details:

  • A DRL file is generated for rule saved from the rule builder UI
  • The DRL is stored as a base64 encoded content in the document repository

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services

/ruleFile

/ruleFile/{ruleId}

get

Retrieves the raw json input data of DRL generator to rerender the rule builder UI in edit scenario. This is the same json which is parsed and converted into a DRL in the /saveRule endpoint.

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services

/fireRules

This resourceType defines the POST method and their responses for a collection resource.

/fireRules

post

Executes multiple rules in real time.

Details:

  • Executes all the relevant rules for the supplied rule type and activity.
  • Calculates points for the supplied member id for the current activity.
  • Sends or schedules emails if emails are configured in the rules which are being executed.
  • Triggers a custom action event if custom actions are configured in the rules which are being executed
  • Response consists of updated points information.

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services

/dummyFire

This resourceType defines the POST method and their responses for a collection resource.

/dummyFire

post

Displays the points that the customer may accrue for an order

Details:

  • Executes all the relevant rules for the supplied rule type and activity.
  • Calculates points for the supplied member id for the current activity.
  • Response consists of updated points information.

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services

/scheduledJobs

This resourceType defines the GET, POST, DELETE methods and their responses for a collection resource.

/scheduledJobs

get

Do not use. Lists all scheduled jobs such as scheduled emails and expiration jobs.

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services

/rewardInfo/{memberId}

This resource type defines the GET method and its responses for a single element resource.

/rewardInfo/{memberId}

get

Gets reward point details for the supplied memberId.

Details:

  • Response contains the current tier details, next tier details, current points balance.
  • This endpoint can be used to project the members progress through the tiers of the Loyalty program.

/customActions

This resourceType defines the GET, POST, DELETE methods and their responses for a collection resource.

/customActions

get

Gets all custom actions

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services
post

Creates a new custom action for rule execution

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services

/customActions/aggr

get

Gets Average, Sum and Count aggregation for custom action

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services

/customActions/{customActionId}

This resource type defines the GET, PUT, DELETE methods and their responses for a single element resource.

get

Gets a specific custom action of a Loyalty program based on the id provided

Accepted scopes:

  • 'sap.loyengine_view' - Perform read operations on Loyalty Rule services
put

Updates a specific custom action based on the id provided

Accepted scopes:

  • 'sap.loyengine_manage' - Perform create and update operations on Loyalty Rule services
delete

Deletes a specific custom action based on the id provided

Accepted scopes:

  • 'sap.loyengine_delete' - Perform delete operations on Loyalty Rule services

/migration

/migration

get

Migrates offer data to relevant format for the latest release

Accepted scopes:

  • 'sap.loyengine_view' - Required to do read operations


Events

For more information about events, see the PubSub service documentation.

The topic owner client is: hybris.loy-rule

EVENT TYPEDESCRIPTIONEXAMPLE
customActionInvokedTriggered when a custom action is invoked during rule processing
{"events":[{"eventType":"customActionInvoked","payload":"{\"tenant\":\"loyqm1605test\",\"customActionId\":\"3a23a8bc752a44daba868aa449a6f84e\",\"eventData\":{\"ruleType\":\"REGISTRATION\",\"member\":{\"memberId\":\"a7a716faee4ec94419f9ae8a897742b7\",\"memberNumber\":\"619854193\",\"programId\":\"a9dd04e1f51e46d99a1afce83284adf1\",\"customerId\":\"C0986307124\",\"customerEmail\":\"lohitstage01@hybristest.com\",\"dateValidFrom\":\"2016-04-14\",\"dateValidTo\":\"2090-05-05\",\"tierId\":\"47f17fb3c2bd4f5fafd3841ae1ffc4a9\",\"tierHistory\":[{\"tierId\":\"47f17fb3c2bd4f5fafd3841ae1ffc4a9\",\"tierUpdateDate\":1.460619854209E12,\"tierActivity\":\"UPGRADE\"}],\"totalEarnedPoints\":0.0,\"totalBalancePoints\":100.0,\"totalQualifyingPoints\":100.0,\"totalExpiredPoints\":0.0,\"createdBy\":\"C0986307124\",\"memberStatus\":\"ACTIVE\",\"preferredLanguage\":\"en\"},\"memberActivity\":{\"memberActivityId\":\"396bb5b60ff84b909d207e6e17d1d966\",\"memberId\":\"a7a716faee4ec94419f9ae8a897742b7\",\"refId\":\"\",\"activityType\":\"REGISTRATION\",\"transactionAmount\":0.0,\"programId\":\"a9dd04e1f51e46d99a1afce83284adf1\",\"tierId\":\"47f17fb3c2bd4f5fafd3841ae1ffc4a9\",\"year\":\"2016\",\"quarter\":\"Q_2\",\"month\":\"APR\",\"week\":16,\"createdBy\":\"C0986307124\",\"activityStatus\":\"NEW\"}},\"pointsData\":{\"membershipId\":\"a7a716faee4ec94419f9ae8a897742b7\",\"qualifyingPointsEarned\":100.0,\"redeemablePointsEarned\":100.0,\"redeemablePointsUsed\":0.0,\"redeemablePointsBalance\":100.0,\"qualifyingPointsBalance\":100.0,\"qualifyingPointsExpired\":0.0,\"redeemablePointsExpired\":0.0,\"processingTime\":\"491ms\",\"processedAt\":\"2016-04-14\",\"newTierId\":\"47f17fb3c2bd4f5fafd3841ae1ffc4a9\",\"rulesApplied\":[\"ecdcbb024a51458893ff9d519b03d261\",\"bee01f10e8174c9cbb44e8c65bee5df9\"]}}","tenant":"loyqm1605test","id":"8ec639c8-123d-4db8-ac7c-db327730592c","sourceClient":"hybris.loy-rule","createdAt":1460619855336}],"token":"eyJ0Z3AiOnsidG9waWMiOiJoeWJyaXMubG95LXJ1bGUuY3VzdG9tQWN0aW9uSW52b2tlZCIsImdyb3VwIjoibG95cW0xNjA1dGVzdC5sb3kxNjA1eW1rdCIsInBhcnRpdGlvbiI6MH0sIm9mZnNldCI6MTgzLCJuZXdPZmZzZXQiOjE4NCwidXVpZCI6Ijg1NGU0MzU5LTJhMTMtNGZlYi05MTM2LTJkMWJjMTJjMDYzNiJ9"}


Error Types

For more information about error codes, see the detailed error description for each API operation in API Reference. You can also check the standard error codes at API best practices.


Scopes

Scopes are strings that let you specify exactly what type of access you need to resources and operations in the Loyalty Rule service.

You must provide a proper scope that enables users to perform certain operations. The scopes should be granted in an access token from OAuth 2.0 service. For more information about the authorization and authentication used in hybris services, and also about the scopes in general, see: Authorization Scopes

The table presents all the scopes supported by the Loyalty Rule service.

ScopeDescription
sap.loyengine_viewUse this scope to view existing rules.
sap.loyengine_manageUse this scope to create or modify existing rules.
sap.loyengine_deleteUse this scope to delete an existing rule.

If a certain operation requires two scopes to be allowed, then your role will need to have these two scopes assigned. Let's see an example where you want to view existing rules and change some properties of the rules and update it:

  1. You want to view a specific loyalty rule and change some of the properties and update it. To do this operation, your role needs the sap.loyengine_view and sap.loyengine_manage scope.
  2. However, if you want to view specific loyalty rule and delete it. To do this operation , your role needs the sap.loyengine_view and sap.loyengine_delete scope.


‘Create/Update/Retrieve a rule’

Introduction

This tutorial is about creating, updating and retrieving rules.

The /saveRule is a mashup endpoint which lets you create a new rule. This endpoint is expected to be used by the Rule Builder UI to create and update rules. This mashup orchestrates the creation of a drools DRL file and saves the rule in document repository.

/ruleFile endpoint retrieves the JSON represntation of the rule.

/rule endpoint lets you retrieve the DRL content of the rule.

To perform the basic operations supported by the Loyalty Rule service, you need to be properly authorized. This is achieved through the header that carries the correct access token. The examples in this tutorial will lead you through those operations, showing what you need to provide to the methods, and what you get in return.

clientId = clientIdPlaceholder;
clientSecret = clientSecretPlaceholder;
tenant = projectIdPlaceholder;
client = appIdPlaceholder;;
scopesRequired = 'hybris.tenant='+tenant+' sap.loyengine_manage sap.loyengine_view sap.loyengine_delete';
token = tokenPlaceholder;
assert = chai.assert;

Get access token

To perform any operations with a specific service, you always need an access token. For this purpose, create an API Client for the oAuth2 service:

API.createClient('oAuth2Service',
'/services/oauth2/v1/api.raml');

Now get the token:

AccessToken = oAuth2Service.token.post({
  'client_id' : clientId,
  'client_secret': clientSecret,
  'grant_type' : 'client_credentials',
  'token_type': 'Bearer',
  'scope': scopesRequired
});
access_token = AccessToken.body.access_token;

Create API client for Loyalty Rule service

API.createClient('ruleService',
'/services/loyaltyrule/v1/api.raml');

Create a new rule

Please note that it is advised to create new rules using the Rule Builder UI instead of API calls. Th creation of a rule requires a JSON input in a very specific format with specific keywords. This is internally handled in the Rule Builder UI.

/saveRule POST will let you create a new rule.This endpoint orchestrates the creation of a DRL file. This DRL content along with other rule data is then saved in the document repository.


response_obj = ruleService.saveRule.post({
  "rule":{
    "ruleId":"New",
    "name":"Tutorial Rule",
    "description":"Tutorial Rule",
    "ruleType":"ORDER",
    "refId":"3fcf90ddcf704d52a8d8da7863d74d11",
    "tiers":[
      "dd17c36127d146dab2036b37e7650ce2"
    ],
    "createdBy":"arun.suresh@sap.com",
    "updatedBy":"arun.suresh@sap.com",
    "ruleStatus":"ACTIVE",
    "validFrom":"2016-07-14T18:30:00.000Z",
    "validTo":"2020-12-30T18:30:00.000Z"
  },
  "ruleFile":{
    "ruleType":"ORDER",
    "rules":{
      "ruleName":"Tutorial Rule",
      "who":[
        {
          "key":"TIER",
          "value":"dd17c36127d146dab2036b37e7650ce2"
        }
      ],
      "when":[
        {
          "key":"ACTIVITY_TYPE",
          "value":"ORDER",
          "metaKey":"ORDER"
        }
      ],
      "actions":[
        {
          "key":"AWARD_POINTS",
          "value":10,
          "metaKey":"AWARD_POINTS"
        },
        {
          "key":"SEND_EMAIL",
          "value":"OrderEmail",
          "metaKey":"SEND_EMAIL"
        }
      ]
    }
  }
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Retrieve the rule's JSON representation by its id

Retrieve the rule by its id to get a JSON representation of the rule.The Rule Builder UI interprets this JSON representation and renders the UI in a user friendly manner.

ruleLocation = response_obj.headers.location.toString();
ruleId = ruleLocation.substring(ruleLocation.lastIndexOf('/')+1,ruleLocation.length);
response = ruleService.ruleFile.ruleId(ruleId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Retrieve the rule's DRL representation by its id

Retrieve the rule by its id to get a DRL representation of the rule. The response body contains the base64 encoded DRL representation of the rule in the ruleFile field.

response = ruleService.rules.ruleId(ruleId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Update the previously created rule

Now update the rule created previously. Please note that the ruleId field in the JSON payload should have the correct rule id generated previously during the POST operation. In this example we are changing the rule status to INACTIVE.


response = ruleService.saveRule.put({
  "rule":{
    "ruleId":ruleId,
    "name":"Tutorial Rule",
    "description":"Tutorial Rule",
    "ruleType":"ORDER",
    "refId":"3fcf90ddcf704d52a8d8da7863d74d11",
    "tiers":[
      "dd17c36127d146dab2036b37e7650ce2"
    ],
    "createdBy":"arun.suresh@sap.com",
    "updatedBy":"arun.suresh@sap.com",
    "ruleStatus":"INACTIVE",
    "validFrom":"2016-07-14T18:30:00.000Z",
    "validTo":"2020-12-30T18:30:00.000Z"
  },
  "ruleFile":{
    "ruleType":"ORDER",
    "rules":{
      "ruleName":"Tutorial Rule",
      "who":[
        {
          "key":"TIER",
          "value":"dd17c36127d146dab2036b37e7650ce2"
        }
      ],
      "when":[
        {
          "key":"ACTIVITY_TYPE",
          "value":"ORDER",
          "metaKey":"ORDER"
        }
      ],
      "actions":[
        {
          "key":"AWARD_POINTS",
          "value":10,
          "metaKey":"AWARD_POINTS"
        },
        {
          "key":"SEND_EMAIL",
          "value":"OrderEmail",
          "metaKey":"SEND_EMAIL"
        }
      ]
    }
  }
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Delete the rule by its id

response = ruleService.rules.ruleId(ruleId).delete(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

  assert.equal(response.status, '204');


Register a custom action

Introduction

You can register a custom action, which a rule can trigger if certain conditions are satisfied. With custom actions you can control the outcome of a rule and trigger your own action instead of the standard actions available in the Rule Builder UI. Implement your own action using any technology, which listens to the customActionInvoked event. The event payload will contain the custom action id which your implementation can then use to perform an appropriate action. /customAction lets you register your custom action, which can be triggered as an outcome of a rule. To perform the basic operations supported by the Loyalty Rule service, you need to be properly authorized. This is achieved through the header that carries the correct access token. The examples in this tutorial will lead you through those operations, showing what you need to provide to the methods, and what you get in return.

clientId = clientIdPlaceholder;
clientSecret = clientSecretPlaceholder;
tenant = projectIdPlaceholder;
client = appIdPlaceholder;
scopesRequired = 'hybris.tenant='+tenant+' sap.loyengine_manage sap.loyengine_view sap.loyengine_delete';
token = tokenPlaceholder;
assert = chai.assert;

Get access token

To perform any operations with a specific service, you always need an access token. For this purpose, create an API Client for the oAuth2 service:

API.createClient('oAuth2Service',
'/services/oauth2/v1/api.raml');

Now get the token:

AccessToken = oAuth2Service.token.post({
  'client_id' : clientId,
  'client_secret': clientSecret,
  'grant_type' : 'client_credentials',
  'token_type': 'Bearer',
  'scope': scopesRequired
});
access_token = AccessToken.body.access_token;

Create API client for Loyalty Rule service

API.createClient('ruleService',
'/services/loyaltyrule/v1/api.raml');

Register a Custom Action


customAction_obj = ruleService.customActions.post({
'customActionId':'','name':'Send an instant message','customActionStatus':'ACTIVE','description':'Send an instant message using IRC'
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Retrieve the Custom Action created with the previous step

customActionLocation = customAction_obj.headers.location.toString();
customActionId = customActionLocation.substring(customActionLocation.lastIndexOf('/')+1,customActionLocation.length);
ruleService.customActions.customActionId(customActionId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Update the Custom Action object

Perform a partial update on the object:

ruleService.customActions.customActionId(customActionId).put({
'customActionId':customActionId,'name':'Send an instant message','customActionStatus':'INACTIVE','description':'Send an instant message using IRC'
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Retrieve the same Custom Action object to ensure that proper information is updated

Get the Custom Action object to make sure that it was updated.

response = ruleService.customActions.customActionId(customActionId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )
  assert.equal(response.body.customActionStatus, 'INACTIVE');

Delete the above iBeacon Major Object

ruleService.customActions.customActionId(customActionId).delete(null, {
  headers: {
   'Authorization': 'Bearer ' + access_token,
  }
})

Retrieve the deleted Custom Action object to ensure it is really deleted

response = ruleService.customActions.customActionId(customActionId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )
  assert.equal(response.status, '404');


‘Executing custom rules with custom attributes’

Introduction

Loyalty Rule service now supports a custom rule type. Using this rule type, you can deifne a rule with custom attributes to create rule conditions as per your business use case. Before running this interactive tutorial make sure that you have created rule of CUSTOM type using the /saveRule api endpoint or via the builder UI.

You can also use custom attributes with other rule types like ORDER, REGISTRATION, TIER and ACTIVITY.

To perform the basic operations supported by the Loyalty Rule service, you need to be properly authorized. This is achieved through the header that carries the correct access token. The examples in this tutorial will lead you through those operations, showing what you need to provide to the methods, and what you get in return.

clientId = clientIdPlaceholder;
clientSecret = clientSecretPlaceholder;
tenant = projectIdPlaceholder;
client = appIdPlaceholder;;
scopesRequired = 'hybris.tenant='+tenant+' sap.loyengine_manage sap.loyengine_view sap.loyengine_delete';
token = tokenPlaceholder;
assert = chai.assert;

Get access token

To perform any operations with a specific service, you always need an access token. For this purpose, create an API Client for the oAuth2 service:

API.createClient('oAuth2Service',
'/services/oauth2/v1/api.raml');

Now get the token:

AccessToken = oAuth2Service.token.post({
  'client_id' : clientId,
  'client_secret': clientSecret,
  'grant_type' : 'client_credentials',
  'token_type': 'Bearer',
  'scope': scopesRequired
});
access_token = AccessToken.body.access_token;

Create API client for Loyalty Rule service

API.createClient('ruleService',
'/services/loyaltyrule/v1/api.raml');

Trigger a dummy fire of custom rules

In this example we will perform a dummy fire on custom rules. This will execute all rules of CUSTOM rule type and calculate loyalty points for the activity, but will not perform any actions like sending emails, offers etc which are configured in the rule. This endpoint can thus be used to predict how many loyalty points can be earned for a particular activity.

Edit the below payload to pass an actual member id, tier id and program id.In this example we are passing two custom attributes STORE_ID and PAYMENT_OPTION. Please note the ruleType and the activityType fields, make sure that you pass both the values as CUSTOM.

The default example here is executing rules of type ORDER and activityType ORDER for a member with id ecd42052569c74f563108c6ac6fa000e , belonging to tier with id dd17c36127d146dab2036b37e7650ce2 and program with id 3fcf90ddcf704d52a8d8da7863d74d11.Change these values to match the ones in your project.

The Response of the dummy fire contains information like the qualyfing points earned, redeemable points earned etc for the current transaction or activity.

memberId = "ecd42052569c74f563108c6ac6fa000e";
tierId = "dd17c36127d146dab2036b37e7650ce2";
programId = "3fcf90ddcf704d52a8d8da7863d74d11";
response = ruleService.dummyFire.post({
"ruleType":"CUSTOM",
  "memberActivity":{
    "createdBy":"SYSTEM",
    "memberActivityId":"",
    "memberId":memberId,
    "quarter":"Q_1",
    "week":1,
    "refId":"",
    "activityType":"CUSTOM",
    "transactionAmount":200,
    "transactionCurrency":"USD",
    "transactionPoints":0,
    "qualifyingPoints":0,
    "rulesApplied":[
      "TEST"
    ],
    "programId":"",
    "tierId":"",
    "discountId":"",
    "updatedBy":"SYSTEM",
    "activityStatus":"ACTIVE",
    "year":"",
    "month":"JAN"
  },
  "member":{
    "createdBy":"C4173571841",
    "customerEmail":"arun.suresh@sap.com",
    "customerId":"C4173571841",
    "dateValidFrom":"2016-04-04T00:00:00.000+0000",
    "dateValidTo":"2090-05-05T00:00:00.000+0000",
    "memberId":"ecd42052569c74f563108c6ac6fa000e",
    "memberNumber":"9743681454",
    "memberStatus":"ACTIVE",
    "preferredLanguage":"en",
    "programId":programId,
    "tierHistory":[
      {
        "tierActivity":"UPGRADE",
        "tierId":"dd17c36127d146dab2036b37e7650ce2",
        "tierUpdateDate":1459743681470
      }
    ],
    "tierId":tierId,
    "totalBalancePoints":953,
    "totalEarnedPoints":1953,
    "totalExpiredPoints":1401,
    "totalQualifyingPoints":552,
    "updatedBy":"SYSTEM"
  },
  "customAttributes":[{"key":"STORE_ID","value":"12345"},{"key":"PAYMENT_OPTION","value":"CASH"}
  ]
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )

Execute custom rules with custom attributes

In this example we will execute custom rules. This will execute all rules for a given rule type and calculate loyalty points for the activity and perform actions like sending emails, offers etc which are configured in the rule.

Edit the below payload to pass an actual member id, tier id and program id.In this example we are passing two custom attributes STORE_ID and PAYMENT_OPTION. Please note the ruleType and the activityType fields. Make sure that you pass both the values as CUSTOM.

The default example here is executing rules of type CUSTOM and activityType CUSTOM for a member with id ecd42052569c74f563108c6ac6fa000e , belonging to tier with id dd17c36127d146dab2036b37e7650ce2 and program with id 3fcf90ddcf704d52a8d8da7863d74d11.Change these values to match the ones in your project.

The response of /fireRules contains information like the qualifying points earned, redeemable points earned etc for the current transaction or activity.

memberId = "ecd42052569c74f563108c6ac6fa000e";
tierId = "dd17c36127d146dab2036b37e7650ce2";
programId = "3fcf90ddcf704d52a8d8da7863d74d11";
response = ruleService.fireRules.post({
  "ruleType":"CUSTOM",
  "memberActivity":{
    "createdBy":"SYSTEM",
    "memberActivityId":"",
    "memberId":"ecd42052569c74f563108c6ac6fa000e",
    "quarter":"Q_1",
    "week":1,
    "refId":"",
    "activityType":"CUSTOM",
    "transactionAmount":200,
    "transactionCurrency":"USD",
    "transactionPoints":0,
    "qualifyingPoints":0,
    "rulesApplied":[
      "TEST"
    ],
    "programId":"",
    "tierId":"",
    "discountId":"",
    "updatedBy":"SYSTEM",
    "activityStatus":"ACTIVE",
    "year":"",
    "month":"JAN"
  },
  "member":{
    "createdBy":"C4173571841",
    "customerEmail":"arun.suresh@sap.com",
    "customerId":"C4173571841",
    "dateValidFrom":"2016-04-04T00:00:00.000+0000",
    "dateValidTo":"2090-05-05T00:00:00.000+0000",
    "memberId":"ecd42052569c74f563108c6ac6fa000e",
    "memberNumber":"9743681454",
    "memberStatus":"ACTIVE",
    "preferredLanguage":"en",
    "programId":"3fcf90ddcf704d52a8d8da7863d74d11",
    "tierHistory":[
      {
        "tierActivity":"UPGRADE",
        "tierId":"dd17c36127d146dab2036b37e7650ce2",
        "tierUpdateDate":1459743681470
      }
    ],
    "tierId":"dd17c36127d146dab2036b37e7650ce2",
    "totalBalancePoints":953,
    "totalEarnedPoints":1953,
    "totalExpiredPoints":1401,
    "totalQualifyingPoints":552,
    "updatedBy":"SYSTEM"
  },
  "customAttributes":[
              {
                  "key":"STORE_ID",
                "value":"12345"
            },
            {
              "key":"PAYMENT_OPTION",
            "value":"CASH"
            }
  ]

}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )


‘Perform a dummy fire of rules’

Introduction

The existing active rules created in the project can be tested by using the dummy fire feature. This API endpoint will execute all rules for a given rule type and calculate loyalty points for the activity, but will not perform any actions like sending emails, offers etc which are configured in the rule. This endpoint can thus be used to predict how many loyalty points can be earned for a particular activity.To perform the basic operations supported by the Loyalty Rule service, you need to be properly authorized. This is achieved through the header that carries the correct access token. The examples in this tutorial will lead you through those operations, showing what you need to provide to the methods, and what you get in return.

clientId = clientIdPlaceholder;
clientSecret = clientSecretPlaceholder;
tenant = projectIdPlaceholder;
client = appIdPlaceholder;;
scopesRequired = 'hybris.tenant='+tenant+' sap.loyengine_manage sap.loyengine_view sap.loyengine_delete';
token = tokenPlaceholder;
assert = chai.assert;

Get access token

To perform any operations with a specific service, you always need an access token. For this purpose, create an API Client for the oAuth2 service:

API.createClient('oAuth2Service',
'/services/oauth2/v1/api.raml');

Now get the token:

AccessToken = oAuth2Service.token.post({
  'client_id' : clientId,
  'client_secret': clientSecret,
  'grant_type' : 'client_credentials',
  'token_type': 'Bearer',
  'scope': scopesRequired
});
access_token = AccessToken.body.access_token;

Create API client for Loyalty Rule service

API.createClient('ruleService',
'/services/loyaltyrule/v1/api.raml');

Trigger a dummy fire

Make sure that you have active rules in your project.Edit the below payload to pass an actual member id, tier id and program id.You can additionally also pass product attributes, order attributes and custom attributes. If you are using any of these attributes in the rule conditions, these will be considered while executing the rules.

The default example here is executing rules of type ORDER and activityType ORDERfor a member with id ecd42052569c74f563108c6ac6fa000e , belonging to tier with id dd17c36127d146dab2036b37e7650ce2 and program with id 3fcf90ddcf704d52a8d8da7863d74d11. Change these values to match the ones in your project.

The response of the dummy fire contains information like the qualifying points earned, redeemable points earned etc for the current transaction or activity.

memberId = "ecd42052569c74f563108c6ac6fa000e";
tierId = "dd17c36127d146dab2036b37e7650ce2";
programId = "3fcf90ddcf704d52a8d8da7863d74d11";
response = ruleService.dummyFire.post({
"ruleType":"ORDER",
  "memberActivity":{
    "createdBy":"SYSTEM",
    "memberActivityId":"",
    "memberId":memberId,
    "quarter":"Q_1",
    "week":1,
    "refId":"",
    "activityType":"ORDER",
    "transactionAmount":200,
    "transactionCurrency":"USD",
    "transactionPoints":0,
    "qualifyingPoints":0,
    "rulesApplied":[
      "TEST"
    ],
    "programId":"",
    "tierId":"",
    "discountId":"",
    "updatedBy":"SYSTEM",
    "activityStatus":"ACTIVE",
    "year":"",
    "month":"JAN"
  },
  "member":{
    "createdBy":"C4173571841",
    "customerEmail":"arun.suresh@sap.com",
    "customerId":"C4173571841",
    "dateValidFrom":"2016-04-04T00:00:00.000+0000",
    "dateValidTo":"2090-05-05T00:00:00.000+0000",
    "memberId":"ecd42052569c74f563108c6ac6fa000e",
    "memberNumber":"9743681454",
    "memberStatus":"ACTIVE",
    "preferredLanguage":"en",
    "programId":programId,
    "tierHistory":[
      {
        "tierActivity":"UPGRADE",
        "tierId":"dd17c36127d146dab2036b37e7650ce2",
        "tierUpdateDate":1459743681470
      }
    ],
    "tierId":tierId,
    "totalBalancePoints":953,
    "totalEarnedPoints":1953,
    "totalExpiredPoints":1401,
    "totalQualifyingPoints":552,
    "updatedBy":"SYSTEM"
  },
  "customAttributes":[
  ],
  "productAttributes":[
    {
      "productId":"56fe2e9448ed90001df646e6",
      "productName":"Fossil Chronograph Black Dial Men's Watch - CH2891",
      "price":200,
      "quantity":1,
      "imageURL":"",
      "productCategory":[
        {
          "name":"Watches",
          "description":"watches",
          "media":[
          ],
          "categoryId":"864139264"
        }
      ],
      "customAttributes":[
      ]
    }
  ],
  "orderAttributes":{
    "transactionCurrency":"USD",
    "total":"",
    "subTotal":"",
    "shippingAmount":"",
    "discountAmount":"",
    "shippingCountry":"",
    "shippingState":"",
    "customAttributes":[
    ]
  }
}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )


‘Execute the rules’

Introduction

The existing active rules created in the project can be executed by using the /fireRules endpoint. This will execute all rules for a given rule type and calculate loyalty points for the activity and perform any actions like sending emails, offers etc which are configured in the rule.To perform the basic operations supported by the Loyalty Rule service, you need to be properly authorized. This is achieved through the header that carries the correct access token. The examples in this tutorial will lead you through those operations, showing what you need to provide to the methods, and what you get in return.

clientId = clientIdPlaceholder;
clientSecret = clientSecretPlaceholder;
tenant = projectIdPlaceholder;
client = appIdPlaceholder;;
scopesRequired = 'hybris.tenant='+tenant+' sap.loyengine_manage sap.loyengine_view sap.loyengine_delete';
token = tokenPlaceholder;
assert = chai.assert;

Get access token

To perform any operations with a specific service, you always need an access token. For this purpose, create an API Client for the oAuth2 service:

API.createClient('oAuth2Service',
'/services/oauth2/v1/api.raml');

Now get the token:

AccessToken = oAuth2Service.token.post({
  'client_id' : clientId,
  'client_secret': clientSecret,
  'grant_type' : 'client_credentials',
  'token_type': 'Bearer',
  'scope': scopesRequired
});
access_token = AccessToken.body.access_token;

Create API client for Loyalty Rule service

API.createClient('ruleService',
'/services/loyaltyrule/v1/api.raml');

Execute rules of a particular rule type

Make sure that you have active rules in your project. Edit the below payload to pass an actual member id, tier id and program id. You can additionally also pass product attributes, order attributes and custom attributes. If you are using any of these attributes in the rule conditions, these will be considered while executing the rules.

The default example here is executing rules of type CUSTOM and activityType CUSTOM for a member with id ecd42052569c74f563108c6ac6fa000e , belonging to tier with id dd17c36127d146dab2036b37e7650ce2 and program with id 3fcf90ddcf704d52a8d8da7863d74d11.Change these values to match the ones in your project.

The response of /fireRules contains information like the qualifying points earned, redeemable points earned etc for the current transaction or activity.

memberId = "ecd42052569c74f563108c6ac6fa000e";
tierId = "dd17c36127d146dab2036b37e7650ce2";
programId = "3fcf90ddcf704d52a8d8da7863d74d11";
response = ruleService.fireRules.post({
  "ruleType":"CUSTOM",
  "memberActivity":{
    "createdBy":"SYSTEM",
    "memberActivityId":"",
    "memberId":"ecd42052569c74f563108c6ac6fa000e",
    "quarter":"Q_1",
    "week":1,
    "refId":"",
    "activityType":"CUSTOM",
    "transactionAmount":200,
    "transactionCurrency":"USD",
    "transactionPoints":0,
    "qualifyingPoints":0,
    "rulesApplied":[
      "TEST"
    ],
    "programId":"",
    "tierId":"",
    "discountId":"",
    "updatedBy":"SYSTEM",
    "activityStatus":"ACTIVE",
    "year":"",
    "month":"JAN"
  },
  "member":{
    "createdBy":"C4173571841",
    "customerEmail":"arun.suresh@sap.com",
    "customerId":"C4173571841",
    "dateValidFrom":"2016-04-04T00:00:00.000+0000",
    "dateValidTo":"2090-05-05T00:00:00.000+0000",
    "memberId":"ecd42052569c74f563108c6ac6fa000e",
    "memberNumber":"9743681454",
    "memberStatus":"ACTIVE",
    "preferredLanguage":"en",
    "programId":"3fcf90ddcf704d52a8d8da7863d74d11",
    "tierHistory":[
      {
        "tierActivity":"UPGRADE",
        "tierId":"dd17c36127d146dab2036b37e7650ce2",
        "tierUpdateDate":1459743681470
      }
    ],
    "tierId":"dd17c36127d146dab2036b37e7650ce2",
    "totalBalancePoints":953,
    "totalEarnedPoints":1953,
    "totalExpiredPoints":1401,
    "totalQualifyingPoints":552,
    "updatedBy":"SYSTEM"
  },
  "customAttributes":[
              {
                  "key":"ACTIVITY",
                "value":"TWEET"
            },
            {
              "key":"HASHTAG",
            "value":"#SAP"
            }
  ],
  "productAttributes":[
    {
      "productId":"56fe2e9448ed90001df646e6",
      "productName":"Fossil Chronograph Black Dial Men's Watch - CH2891",
      "price":200,
      "quantity":1,
      "imageURL":"",
      "productCategory":[
        {
          "name":"Watches",
          "description":"watches",
          "media":[
          ],
          "categoryId":"864139264"
        }
      ],
      "customAttributes":[
      ]
    }
  ],
  "orderAttributes":{
    "transactionCurrency":"USD",
    "total":"",
    "subTotal":"",
    "shippingAmount":"",
    "discountAmount":"",
    "shippingCountry":"",
    "shippingState":"",
    "customAttributes":[
    ]
  }

}, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )


‘Retrieve the progress of a loyalty member’

Introduction

The /rewardInfo endpoint lets you project where the current Loyalty member stands in the loyalty program. The response contains the current tier details, next tier details, current points balance for the supplied member id. This information can be used to project the member's progress through the various tiers of the loyalty program. In order to accurately calculate the progress of the member, a loyalty program must be defined with tiers and tier rules must be set up with details on when to upgrade/downgrade a tier. To perform the basic operations supported by the Loyalty Rule service, you need to be properly authorized. This is achieved through the header that carries the correct access token. The examples in this tutorial will lead you through those operations, showing what you need to provide to the methods, and what you get in return.

clientId = clientIdPlaceholder;
clientSecret = clientSecretPlaceholder;
tenant = projectIdPlaceholder;
client = appIdPlaceholder;;
scopesRequired = 'hybris.tenant='+tenant+' sap.loyengine_manage sap.loyengine_view sap.loyengine_delete';
token = tokenPlaceholder;
assert = chai.assert;

Get access token

To perform any operations with a specific service, you always need an access token. For this purpose, create an API Client for the oAuth2 service:

API.createClient('oAuth2Service',
'/services/oauth2/v1/api.raml');

Now get the token:

AccessToken = oAuth2Service.token.post({
  'client_id' : clientId,
  'client_secret': clientSecret,
  'grant_type' : 'client_credentials',
  'token_type': 'Bearer',
  'scope': scopesRequired
});
access_token = AccessToken.body.access_token;

Create API client for Loyalty Rule service

API.createClient('ruleService',
'/services/loyaltyrule/v1/api.raml');

Find the loyalty member's progress in the Loyalty Program

Make sure that you have active tier rules in your project. Edit the below payload to pass an actual member id.

The default example here calculates the progress of a loyalty member with id ecd42052569c74f563108c6ac6fa000e. Change this value to match an existing member in your project.

The response of the /rewardInfo contains information like the current tier details, next tier details, current points balance for the supplied member id.

memberId = "ecd42052569c74f563108c6ac6fa000e";

response = ruleService.rewardInfo.memberId(memberId).get(null, {
  headers: {
    'Authorization': 'Bearer ' + access_token,
    'Content-type' : 'application/json'
           }
    }
  )


  • Send feedback

    If you find any information that is unclear or incorrect, please let us know so that we can improve the Dev Portal content.

  • Get Help

    Use our private help channel. Receive updates over email and contact our specialists directly.

  • hybris Experts

    If you need more information about this topic, visit hybris Experts to post your own question and interact with our community and experts.