Skip to content

🚨 Important Lab Dependency

This mission requires configuration created in the following missions:

  1. NO DEPENDENCY

Mission 5: Personalized Customer Notification with Functions

Story

In this mission, you will use a Function node in Webex Contact Center to retrieve customer data from an external database and generate a personalized message using JavaScript. This ensures callers receive real-time updates on their last purchase, outstanding balance, and service requests without agent intervention.

Call Flow Overview

  1. When call arrives fetch the data from MockAPI based on your Dialed Number.
  2. Write the data into respective preconfigured flow variables. These variables will be passed to a Function.
  3. Function will generate a message based on inputs and pass it back to your flow.
  4. Play Message node plays the message received from Function.

Mission Details

Your mission is to:

  1. Create a function that retrieves input variables, processes them, and generates a customer-friendly message.
  2. Create a new flow with the Function element.
  3. Request data from an external database, parse it into flow variables, and pass them to your Function.
  4. Play the message generated by the Function to the caller.

Good to Know [Optional] We are going to imitate a real API server by providing realistic responses to requests. For that we chose Server MockAPI.

For more information of how you can use MockAPI please watch these Vidcasts:

Building Function

  1. Switch to Control Hub, then navigate to Functions, click on Create a function.

  2. New Tab will be opened. Select Start Fresh and provide name Function_Your_Attendee_ID. Leave Function Language as JavaScript, then click Create Function.

    Profiles

  3. Add following variables by clicking Add Input Variables on the right-hand side:

    • Last purchase date variable:

    Name: lastPurchase

    Type: String

    • Customer pending request variable:

    Name: pendingServiceRequest

    Type: String

    • Expected resolution date variable:

    Name: resolutionDate

    Type: String

    • Outstanding account balance variable:

    Name: outstandingBalance

    Type: String

  4. Add output variable personalizedMessage in Output Variable Definition field.

    Profiles

  5. Clear the editor from the default code and paste the following JavaScript code into Function editor.

     export const handle = async (request, response) => {
        // Retrieve input variables (all as strings)
        var lastPurchase = request.inputs.lastPurchase;  // e.g., '17-03-2025'
        var outstandingBalance = request.inputs.outstandingBalance;  // e.g., '120.50'
        var pendingServiceRequest = request.inputs.pendingServiceRequest;  // e.g., 'Network issue'
        var resolutionDate = request.inputs.resolutionDate;  // e.g., '20-03-2025'
    
        // Convert outstandingBalance to a number safely
        let balanceAmount = parseFloat(outstandingBalance);
        if (isNaN(balanceAmount)) {
            balanceAmount = 0;  // Default to 0 if conversion fails
        }
    
        // Function to convert 'DD-MM-YYYY' to a proper Date object
        function parseDate(dateString) {
            if (!dateString) return null;
            const parts = dateString.split('-'); // Split "17-03-2025" into ["17", "03", "2025"]
            if (parts.length !== 3) return null; // Invalid format
    
            const [day, month, year] = parts.map(num => parseInt(num, 10));
            return new Date(year, month - 1, day); // Month is 0-based in JS Dates
        }
    
        // Format the date to a readable string (e.g., "March 17, 2025")
        function formatDate(date) {
            return date ? date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }) : null;
        }
    
        // Parse and format dates
        let formattedLastPurchase = formatDate(parseDate(lastPurchase));
        let formattedResolutionDate = formatDate(parseDate(resolutionDate));
    
        // Generate the personalized message
        let message = 'Hello, we have some information about your account:';
    
        if (formattedLastPurchase) {
            message += ` Your last purchase was on ${formattedLastPurchase}.`;
        }
        if (balanceAmount > 0) {
            message += ` You have an outstanding balance of $${balanceAmount.toFixed(2)}.`;
        }
        if (pendingServiceRequest) {
            message += ` We also have a pending service request: ${pendingServiceRequest}`;
            if (formattedResolutionDate) {
                message += `, resolution by ${formattedResolutionDate}.`;
            } else {
                message += `.`;
            }
        } else {
            message += ' There are no pending service requests at the moment.';
        }
    
        // Return the generated message
        response.data = { 'personalizedMessage': message };
    
        return response;
        };
    

    Profiles

    Good to know: Script Breakdown [Optional] This script dynamically generates a personalized message for customers based on their account details. In our lab it is a Channel Support Number assigned to you. It is used within Webex Contact Center Flow Designer to enhance customer interactions.

    1. How It Works:
      Retrieves input variables from the Flow:

      • lastPurchase → Date of the last purchase (e.g., "17-03-2025").
      • outstandingBalance → The amount owed by the customer (e.g., "120.50").
      • pendingServiceRequest → Details of any unresolved service request (e.g., "Network issue").
      • resolutionDate → Expected resolution date of the service request (e.g., "20-03-2025").
    2. Processes and formats the data:

      • Converts lastPurchase and resolutionDate from "DD-MM-YYYY" format into a more readable format (March 17, 2025).
      • Ensures outstandingBalance is a valid number and avoids errors if it’s missing or invalid.
    3. Generates a customer-friendly message:

      • If the customer made a purchase, the date is included.
      • If an outstanding balance exists, the amount is shown.
      • If there’s a pending service request, it’s mentioned, along with a resolution date (if available).
      • If no pending issues exist, it confirms that everything is fine.
    4. Returns the message to be used in the Flow:

      • The script outputs personalizedMessage, which can be read out in an IVR or displayed to an agent.
  • Perform a test to see how you script preforms by navigating to Test panel below the editor. Provide the following data into respective fields, then click Test button.

    lastPurchase: 17-03-2025

    pendingServiceRequest: Network issue on Amsterdam location

    resolutionDate: 20-03-2025

    outstandingBalance: 529.51

  • Click on Publish Function in the bottom right corner of the page. Then click Publish Function in pop up window.

    Profiles


  • Building Flow

    1. Switch to Control Hub, then navigate to Flows, click on Manage Flows then select Create Flows from drop down list.

    2. Select Start Fresh then enter flow name FunctionFlow_Your_Attendee_ID and click on Create Flow.

      Profiles

    3. Add these flow variables:

      • Last purchase date variable:

      Name: lastPurchase

      Type: String

      Default Value: leave it empty

      • Customer pending request variable:

      Name: pendingServiceRequest

      Type: String

      Default Value: leave it empty

      • Expected resolution date variable:

      Name: resolutionDate

      Type: String

      Default Value: leave it empty

      • Outstanding account balance variable:

      Name: outstandingBalance

      Type: String

      Default Value: leave it empty

      • HTTP Response variable:

      Name: HTTPResponse

      Type: String

      Default Value: leave it empty

      • Personalized message variable:

      Name: personalizedMessage

      Type: String

      Default Value: leave it empty

      Profiles

      Test your API Source [Optional]

      1. Test your API resource. https://674481b1b4e2e04abea27c6e.mockapi.io/flowdesigner/Lab/DynVars?dn={DNIS}

      2. Replace DNIS with the provided DNIS number stripping +1. [For example:] If your number +14694096861, then your GET Query should be https://674481b1b4e2e04abea27c6e.mockapi.io/flowdesigner/Lab/DynVars?dn=4694096861

      3. Open Chrome browser, paste your Get query URL into the Browser address line and press Enter. You should get the JSON response like this:

        Profiles

      4. Open the new browser tab and navigate to JSONPath Online Evaluator

      5. Copy the JSON response (including square brackets) you obtained above and paste it into Document window of JSONPath Online Evaluator.

      6. In JSONPath box copy and paste one of the path expression from FetchFlowSettings to verify your results. For example, $[0].businessHours

        Profiles

    4. Add an HTTP Request node. We are going to fetch data and write it into our new created variables lastPurchase, pendingServiceRequest, resolutionDate and outstandingBalance.

      Connect NewPhoneContact to this HTTP node

      We will connect HTTP Request node in next step

      Activity Name: GET_HTTPRequest

      Use Authenticated Endpoint: Off

      Request URL: https://674481b1b4e2e04abea27c6e.mockapi.io/flowdesigner/Lab/DynVars?dn={{NewPhoneContact.DNIS | slice(2) }}

      Method: GET

      Content Type: Application/JSON

      Parsing Settings:

      Content Type: JSON

      Output Variable: pendingServiceRequest

      Path Expression: $[0].pendingServiceRequest

      Click + Add New

      Output Variable: lastPurchase

      Path Expression: $[0].lastPurchase

      Click + Add New

      Output Variable: outstandingBalance

      Path Expression: $[0].outstandingBalance

      Click + Add New

      Output Variable: resolutionDate

      Path Expression: $[0].resolutionDate

      Profiles

    5. Add Set Variable node

      Activity Label: HTTP_Response

      Connect GET_HTTPRequest you added at the previous step to this node

      We will connect this Set Variable node in next step

      Variable: HTTPResponse

      Set Variable: GET_HTTPRequest.httpResponseBody

      Profiles

    6. Switch to Functions tab at the panel on the left-hand side. Then drag Function_Your_Attendee_ID node to the canvas.

      Connect HTTP_Response node you added at the previous step to this node

      We will connect this node in next step

      Function Version Label: Latest

      Function Input Variables should auto populate

      Output Settings

      Output Variable: personalizedMessage

      Path Expression $.personalizedMessage

      Profiles

    7. Switch to Activity tab in the left menu. Add Play Message and Disconnect Contact nodes

      Connect the Function node edge to the Play Message node

      Enable Text-To-Speech

      Select the Connector: Cisco Cloud Text-to-Speech

      Click Add Text-to-Speech Message button

      Delete the selection for Audio File

      Text-to-Speech Message: {{personalizedMessage}}

      Connect the Play Message node edge to this Disconnect Contact node

    8. Validate and publish the flow:

      Enable the Validation toggle in the bottom right corner of the flow designer window to check for any potential flow errors and recommendations.

      If there are no Flow Errors after validation is complete, click on Publish Flow next to it.

      In the pop-up window, ensure that the Latest label is selected in the Add Version Label(s) list, then click Publish Flow.

      Profiles

    9. Map your flow to your inbound channel

      Navigate to Control Hub > Contact Center > Channels

      Locate your Inbound Channel (you can use the search): Your_Attendee_ID_Channel

      Select the Routing Flow: FunctionFlow_Your_Attendee_ID

      Select the Version Label: Latest

      Click Save in the lower right corner of the screen

      Profiles

    Testing

    1. Open your Webex App and dial the Support Number provided to you, which is configured in your Your_Attendee_ID_Channel configuration.

      profiles

    2. Verify if you hear a message built inside your function.

    3. Switch to Flow Designer and click Debug tab at the bottom and select last interaction (the first in the list).

    4. Click on GET_HTTPRequest and on the right hand side window scroll to the bottom. Check if Modified Variables have values assigned.

    5. Click on HTTP_Response to see full HTTP response body in Modified Variables.

    6. Click on Function step and check if Modified Variables contains personalizedMessage built by your function.

      Profiles


    Congratulations, you have succesfully completed Personalized Customer Notification with Functions mission! 🎉🎉