CRM and CX Blogs by Members
Find insights on SAP customer relationship management and customer experience products in blog posts from community members. Post your own perspective today!
cancel
Showing results for 
Search instead for 
Did you mean: 
tokgozatakan
Participant

Introduction

SAP Sales and Service Cloud Version 2 provides KPI Cards inside Account Details, which are called "Key Metrics". Key Metrics provide quick information about the transactional documents of the account displayed.

Standard Key MetricsStandard Key Metrics

Besides SAP Delivered KPI Cards, you have the option to create your own Key Metrics by fetching the data from outside, into SAP's pre-delivered templates. In this example we will be using Kyma Serverless Functions and API Rules to create our own Customer Key Metrics. The example will cover both Sales and Service Cloud Version 2 configuration and the Kyma Configuration. 

Before we start, I'd like to express that Custom Key Metrics can work with any language, as long as you can parse and return JSON a payload. You may have an analytics application on your hand, you may have Integration Suite knowledge and they would work just as well. The reason I went with Kyma is because it handles all the DevOps for you, automatically scales and provides secure ways of exposing your functions. 

 

Prerequisites

Before we have can start our example, please make sure that you are fulfilling the prerequisites below. 

  • Sales and Service Cloud Version 2 Tenant
  • Kyma Environment Enabled in SAP BTP - You can create a Kyma Enviroment in a trial account as a test case. 
  • Basic Javascript/Python knowledge - as a matter of fact, I did not code the function myself, but prompted it via Gemini AI, with few modifications, it was ready to go!
  • Review the SAP Documentation on how to create the Custom Key Metrics

Creating the Custom Key Metric

In our example we will create a custom key metric that will show how many leads are created from which sources for this account. Picture below shows the final result in an account page.

2024-02-23_22h35_16.png

Technical Flow in a Nutshell

To explain how the Custom Key Metrics works:

  • SAP Provides KPI Templates such as Bar Chart, Pie Chart or Indicator.
  • The templates are bound to a specific JSON Object (see SAP Documentation).
  • When you enter the account, an HTTP POST Request is sent to the endpoint that you have configured.
  • The script/iFlow/Application behind the endpoint is receiving the POST Request, doing its magic, and fills out the payload mentioned above. 
  • System renders the payload that you have returned as a Key Metric. 

 

//Example Pie chart JSON Object that needs to be returned in the payload
{
    "total": "{calculated results}",
    "data": [
        {
            "name": "{description}",
            "y": "{calculated result}"
        },
        {
            "name": "{description}",
            "y": "{calculated result}"
        }
//and so on...
    ]
}

 

 

Configuration On Kyma

Before going to Sales and Service Cloud Version 2, first we need to create our function and endpoint on Kyma, as we need to provide this information in the System.

Open your Kyma Environment, go to your desired namespace. 

Create Your Function

Go to Workloads -> Functions -> + Create Function

2024-02-21_21h23_24.png

  • Give a name to your function.
  • Select Javascript (you also have the option to use Python)
  • Select the latest Node.js Runtime
  • Do not modify the source code - we will do it later.
  • In the dependencies section, enter the values shown in picture. This will enable those libraries in your function. 

Note: In our example "lodash" library is not used and does not need to be added. But in general, it is a useful library for object manipulation. 

  • Click on Create

We now have a serverless function available. The next step is to add some environment variables to make this function easily maintainable across different namespaces (like dev-test-prod) without changing the source code. 

We are going to add the following environment variables for our example:

  • Sales and Service Cloud Version 2 URL (Custom Variable)
  • Sales and Service Cloud Version 2 API Username (Secret Variable)
  • Sales and Service Cloud Version 2 API Password (Secret Variable)

Create Secret Variables

Secrets provide a secure and easy way to access your credentials in Kyma Environment. You can declare them as variables in your code and manage them centrally, without modifying your source code. 

In Kyma, go to Configuration -> Secrets -> Create Secret

2024-02-21_21h31_00.png

  • Give a name for your secret - it is just an internal name; you can generate a random one. 
  • Select Opaque as type.
  • In Data section, add two keys as "username" and "password".
  • The values should be the credentials of a valid API user from your SSCv2 system. I'd recommend a technical user. If you don't have one yet, go to Creating Communication System section in our blog. 
  • Click Create.

You now have a secret that you can use in any function that you create. 

Adding Environment Variables to Your Function

Go back to your function, click on edit and on the environment variable section, add the following values as shown below.

2024-02-21_21h32_01.png

YAML:

 

  env:
    - name: CNS_SECRET
      valueFrom:
        secretKeyRef:
          key: password
          name: cns-key-insights-user
    - name: CNS_USERNAME
      valueFrom:
        secretKeyRef:
          key: username
          name: cns-key-insights-user
    - name: CNS_URL
      value: https://YOURCNSTENANT/sap/c4c/api/v1

 

Now we can fetch these environment variables in our code: 

 

//environment variables
const cnsSecret = process.env.CNS_SECRET;
const cnsUsername = process.env.CNS_USERNAME;
const cnsUrl = process.env.CNS_URL;

 

 

Creating an API Rule 

With API Rules, we can create an endpoint for our functions - or our services in general. We are able to define different paths, routed to different functions with different security options for each path. 

Go to Discovery and Network -> API Rules -> Create API Rule

2024-02-21_21h39_51.png

  • Give a name for your API Rule - it is just an internal name; you can generate a random one. 
  • Leave the Service empty, unless you want to assign a single rule to a single function. We will be assigning the service on the path level. 
  • For the host, give a meaningful name for your function. This will be the main link that you will configure in communication settings. 
  • Go to Rules section.

2024-02-21_21h40_31.png

  • Define a meaningful path name, this will be the path that you will define in Custom Key Metric Settings.
  • In the Access Strategies, you can secure your API Path. "Allow" means anyone can access the link and should only be used for development purposes. In our example we will be using JWT. If you are using IAS, you can provide the information below.
  • For method, we only need POST. 

YAML:

 

    - accessStrategies:
        - config:
            jwks_urls:
              - https://youriastenant.accounts.ondemand.com/oauth2/certs
            trusted_issuers:
              - https://youriastenant.accounts.ondemand.com
          handler: jwt
      methods:
        - POST

 

  • In the Service (under the Access Strategy), select your function.

Modify the Function

Now that we have everything ready, we can finalize our function. Go back to the function you have created. 

Click edit and add the source code below:

 

const axios = require('axios');

// Load environment variables
const cnsSecret = process.env.CNS_SECRET;
const cnsUsername = process.env.CNS_USERNAME;
const cnsUrl = process.env.CNS_URL;

module.exports = {
  main: async function (event, context) {
    try {
      console.log('Event Received:', JSON.stringify(event.data));

      // Extract businessPartnerId from event data
      const businessPartnerId = event.data.businessPartnerId;

      // Define parameters object
      const params = {
        '$filter': `account.id eq '${businessPartnerId}'`,
        '$select': 'name,id,sourceDescription'
      };

      // Perform GET request with basic authentication and parameters
      const leadResponse = await axios.get(`${cnsUrl}/lead-service/leads`, {
        auth: {
          username: cnsUsername,
          password: cnsSecret,
        },
        params,
      });

      // Extract leads data
      const leads = leadResponse.data.value;
      console.log("Fetched Leads: "+JSON.stringify(leads))

      // Calculate total count of leads
      const total = leads.length;
      console.log("Count of Leads: "+JSON.stringify(total))

      // Group leads by sourceDescription and count occurrences
      const groupedData = leads.reduce((acc, lead) => {
        const name = lead.sourceDescription;
        acc[name] = (acc[name] || 0) + 1;
        return acc;
      }, {});

      console.log("groupedData: "+JSON.stringify(groupedData));

      // Convert object to array with name and count
      const data = Object.entries(groupedData).map(([name, count]) => ({ name, y: count }));

      // Construct response payload
      const payload = {
        total,
        data,
      };
      console.log(JSON.stringify(payload));
      return payload;
    } catch (error) {
      console.error(error);
      return { error: error.message };
    }
  },
};

 

As mentioned earlier, this code has been generated by AI, and slightly modified by hand. As long as you give a strong prompt, AI can handle these simple scripts really well.

Here's my example prompt:

 

/*
I need you to write me a nodejs script, which will be used in Kyma environment, you can refer to https://github.com/kyma-project. I have the following config yaml, with some environment variables. I need you to save these environments variables as a constant in the code to be used. You may use axios and lodash libraries.

env:
    - name: CNS_SECRET
      valueFrom:
        secretKeyRef:
            name: cns-key-insights-user
            key: password
    - name: CNS_USERNAME
      valueFrom:
        secretKeyRef:
            name: cns-key-insights-user
            key: username
    - name: CNS_URL
      value: https://host/sap/c4c/api/v1
schemaVersion: v0

Code will be triggered via an HTTP Request Event. When the event gets triggered, log the event headers and data separately. 

example event data: {"businessPartnerId":"11edee65-fccb-955e-afdb-817c5e020a00","billingDocumentId":null,"top":0,"sortBy":null,"idType":null,"language":"en"}

Make a GET request to /lead-service/leads path. for URL, use the constant you have created for CNS_URL environment variable. 

Use the query parameter: $filter=account.id eq '{businessPartnerId from event}'

Count the total of records returned. Add it into "total" key of the payload. Count the sourceDescription, group the sourceDescription, add it into "data" array of the response payload. "name" should be the grouped sourceDescription, y should is the count of the grouped sourceDescription. 

Return the following payload in the end. 

{
    "total": "{count of leads}",
    "data": [
        {
            "name": "{sourceDescription1}",
            "y": "{count of sourceDescription1}"
        },
        {
            "name": "{sourceDescription2}",
            "y": "{count of sourceDescription2}"
        }
    ]
}
*\

 

Now that we have our code up and running, it is time to configure the Sales and Service Cloud Version 2 side. 

Of course, always treat these codes cautiously as AI tends to make a lot of mistakes. Also, make sure to test different cases and modify your code accordingly to handle those cases. 

 

Configuring Sales and Service Cloud Version 2 for Custom Key Metrics

Once you have everything ready on Kyma side, configuration on CNS side (Cloud Native Stack - a.k.a. Sales and Service Cloud Version 2) will come pretty easily. 

Creating a Communication System

If you would like to use a specific user for Key Insights (which I'd recommend) you need to create a new Communication System. 

Go to Settings -> Integration -> Communication Systems and click on plus (+) icon.

2024-02-21_21h11_21.png

Inbound settings will create a technical user that you will use to fetch data from the APIs of your CNS Tenant. Set up a password and click on Save and Activate. Your technical user with the same name will be created in the background. 

Click edit on your communication system and open the Outbound settings.

2024-02-21_21h17_11.png

Outbound setting is where you fill in the receiver system's credentials and link.

Host Name: Add the link that you created in the Kyma API Rules. Do not add paths (/example/path). 

Authentication Method: For the authentication, if you have followed the blog and used JWT, then use your IAS OAuth Client Credentials as shown above. To create your own IAS OAuth Keys, click here.  

Creating Custom Key Metrics

Go to Settings -> Customer Insights -> Custom Key Metrics and click on plus (+) icon.

2024-02-21_22h00_56.png

Key Metric Name: Administrative name of the key metric

Key Metric Title: The name that you will see in Accounts Key Metrics section.

Chart Type: Choose Pie, as we have used that payload type in the function.

API Path: Use the path that you have defined for your function in the API Rules. 

Communication System: Select the system that you have created earlier.

Navigation URL: If you want to launch a specific link, you can place it here. 

Click Save. Now you have configured your custom key metric!

Testing the Custom Key Metrics

To test your Key Metrics, go to any Accounts that have leads. On the Key Metrics section, custom key metrics will be on the last cards. 

You can trace the network logs by searching "key-metrics".

2024-02-28_22h25_47.png

In the Kyma logs, you can trace your function real time and see any errors that come up.  

2024-02-28_22h27_33.png

 

Conclusion

Now you have a functioning Key Metric at your service! Good thing is, first one is actually the most time consuming but for the future, you can re-use the first one as a template for the other key metrics that you can create. 

1 Comment