提供: Bright Pattern Documentation
移動先: 案内、 検索
• English

Salesforce Flow から Bright Pattern タスクを作成する方法

Salesforce Flow とカスタム Apex アクションを使用して、Bright Pattern タスクの作成をトリガーすることができます。本ガイドでは、Apex アクション を設定し、Salesforce Flow から呼び出すための設定例を紹介します。

前提条件

  • Salesforce 組織への管理者権限。
  • Bright Pattern コンタクトセンターへの管理者権限。
  • API を使用するための Bright Pattern ユーザーを設定済みであり、API シークレット および「タスクルーティング API を使用する」ユーザー権限 が有効になっていること。
  • Bright Pattern 内に設定済みの タスクシナリオエントリー があり、その 一意の識別子 を taskLaunchPointId として使用すること。


ステップ 1: API 設定の安全な保管

単一の 保護されたカスタム設定 に、必要な設定をすべて格納します。これにより、機密情報が安全に保護され、1 か所から統合を簡単に管理できるようになります。

  1. Salesforce の設定画面で、「カスタム設定」 を検索して選択します。

  2. [新規] をクリックします。

  3. 以下の詳細を入力します:
    • ラベル:Bright Pattern Config
    • オブジェクト名:Bright_Pattern_Config
    • 設定タイプ:階層
    • 表示設定: 保護済み

  4. [保存] をクリックします。

  5. [カスタム設定] ページの [カスタム項目] セクションで [新規] をクリックし、以下のフィールドを追加します:
    • データ型:テキスト、フィールドラベル:Client ID (Username)、長さ:255
    • データ型:テキスト、フィールドラベル:Client Secret (API Secret)、長さ:255
    • データ型:テキスト、フィールドラベル:Task Launch Point ID、長さ:255
    • データ型:URL、フィールドラベル:Token Endpoint、長さ:255
    • データ型:URL、フィールドラベル:Task API Endpoint、長さ:255

  6. フィールドを作成したら、Bright Pattern Config ページ上部の [管理] ボタンをクリックします。

  7. 上部の「Default Organization Level Value」の隣にある [新規] をクリックします。

  8. 各フィールドに、Bright Pattern コンタクトセンターの詳細情報を入力します:
  9. [保存] をクリックします。


ステップ 2: Invocable Apex クラスの作成

この Apex クラスには、Bright Pattern でタスクを作成するためのロジックが含まれています。このクラスは、認証とルーティングを安全に処理するために、前ステップで作成した「保護されたカスタム設定」から taskLaunchPointId を含むすべての設定を取得します。

  1. Salesforce の設定画面で「Apex クラス」を検索して選択します。

  2. [新規] をクリックし、クラス作成の例として以下のコードを使用します:

    /*
    This class contains an Invocable Apex Action for a Salesforce Flow. Its purpose is
    to queue a task in the Bright Pattern system by making a callout to their API.
    
    An important security note: The user running the Flow that calls this Apex action 
    must have the appropriate permissions to the Bright_Pattern_Config__c custom setting.
    */
    public with sharing class BrightPatternTaskController {
    
        // This is a custom exception class to provide more specific error details from this controller.
        public class BrightPatternException extends Exception {}
    
        // This inner class defines the input variables that will be exposed in the Flow Builder.
        // The Flow will pass data into an instance of this class.
        public class FlowRequest {
    
          @InvocableVariable(label="Case ID for Screenpop" required=true)
          public String caseId;
    
          @InvocableVariable(label="Case Number" required=true)
          public String caseNumber;
    
          @InvocableVariable(label="Contact ID" required=true)
          public String contactId;
    
          @InvocableVariable(label="Task Subject" required=true)
          public String subject;
    
          @InvocableVariable(label="Task Priority")
          public String priority;
        }
    
        /*
        This method is exposed to the Flow Builder as an Apex Action.
        It takes a list of requests from the Flow and queues a corresponding task in Bright Pattern.
        */
        @InvocableMethod(label="Queue Bright Pattern Task", description="Queues a task in Bright Pattern via the API." category="Bright Pattern")
        public static void queueTaskInBrightPattern(List<FlowRequest> requests) {
    
          // Retrieve all configuration from the Protected Custom Setting.
          Bright_Pattern_Config__c bpConfig = Bright_Pattern_Config__c.getOrgDefaults();
    
          // Check for valid configuration and throw a clear error if anything is missing.
          // This provides immediate feedback to the Flow administrator if the setup is incomplete.
          if (bpConfig == null || String.isBlank(bpConfig.Task_Launch_Point_ID__c) || String.isBlank(bpConfig.Task_API_Endpoint__c) || String.isBlank(bpConfig.Token_Endpoint__c) || String.isBlank(bpConfig.Client_ID__c) || String.isBlank(bpConfig.Client_Secret__c)) {
            throw new AuraHandledException("Bright Pattern configuration is missing or incomplete in Custom Settings. Please check the configuration.");
          }
    
          try {
              // Get the access token once for this entire transaction.
              String accessToken = getAccessToken(bpConfig);
              if (String.isBlank(accessToken)) {
                // Throw an exception that the Flow can handle if the token request fails.
                throw new BrightPatternException("Failed to obtain a Bright Pattern Access Token.");
              }
    
              // Even though we often expect one request per invocation from a Flow,
              // we loop through the list, as this is the best practice for Invocable Methods.
              for (FlowRequest req : requests) {
                
                Http http = new Http();
                HttpRequest apiRequest = new HttpRequest();
                
                apiRequest.setEndpoint(bpConfig.Task_API_Endpoint__c);
                apiRequest.setMethod("POST");
                apiRequest.setHeader("Authorization", "Bearer " + accessToken);
                apiRequest.setHeader("Content-Type", "application/json;charset=UTF-8");
    
                // Construct the request body from the Flow inputs.
                Map<String, Object> bodyMap = new Map<String, Object>{
                  "taskLaunchPointId" => bpConfig.Task_Launch_Point_ID__c,
                  "extTaskId" => req.caseNumber,
                  "extContactId" => req.contactId,
                  "priority" => req.priority,
                  "taskInfo" => new Map<String, String>{ "subject" => req.subject },
                  "screenpop" => "SHOW_OBJECT:" + req.caseId + ":Case"
                };
                
                apiRequest.setBody(JSON.serialize(bodyMap));       
    
                HttpResponse response = http.send(apiRequest);
    
                // Check the response and throw an exception on failure.
                // This will halt the Flow and display an error, preventing silent failures.
                if (response.getStatusCode() != 200) {
                    String errorMessage = "Failed to queue task in Bright Pattern. Status: " + response.getStatus() + ". Body: " + response.getBody();
                    System.debug(errorMessage);
                    throw new BrightPatternException(errorMessage);
                } else {
                    System.debug("Successfully queued task: " + response.getBody());
                }
              }
          } catch (Exception e) {
              // This is a centralized exception handler.
              // It catches any exceptions thrown from the logic above (like CalloutException or our custom BrightPatternException).
              // It then re-throws them as an AuraHandledException to make them visible in the Flow's fault path.
              System.debug("An error occurred in BrightPatternTaskController: " + e.getMessage() + " Stacktrace: " + e.getStackTraceString());
              throw new AuraHandledException(e.getMessage());
          }
        }
    
        // This is a helper method to get the access token using securely stored credentials.
        // It takes the Bright Pattern configuration custom setting as its input.
        // It returns the access token string.
        private static String getAccessToken(Bright_Pattern_Config__c config) {
    
          HttpRequest tokenRequest = new HttpRequest();
          tokenRequest.setEndpoint(config.Token_Endpoint__c);
          tokenRequest.setMethod("POST");
          tokenRequest.setHeader("Content-Type", "application/x-www-form-urlencoded");
    
          // The scope is derived from the Token Endpoint URL. For Bright Pattern, this is the tenant URL.
          String tenantUrl = new URL(config.Token_Endpoint__c).getHost();
    
          String requestBody = "grant_type=client_credentials"
                   + "&client_id=" + EncodingUtil.urlEncode(config.Client_ID__c, "UTF-8")
                   + "&client_secret=" + EncodingUtil.urlEncode(config.Client_Secret__c, "UTF-8")
                   + "&scope=" + EncodingUtil.urlEncode(tenantUrl, "UTF-8");
    
          tokenRequest.setBody(requestBody);
          
          Http http = new Http();
          HttpResponse tokenResponse = http.send(tokenRequest);
    
          if (tokenResponse.getStatusCode() == 200) {
            Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(tokenResponse.getBody());
            return (String) result.get("access_token");
          } else {
            // Log the detailed error but return null so it can be handled by the calling method.
            System.debug("Token request failed. Status: " + tokenResponse.getStatus() + ". Body: " + tokenResponse.getBody());
            return null;
          }
        }
    }
    
  3. クラスを保存します。

ステップ 3: Salesforce フローを作成する

フローは、Apex アクションをトリガーするビジネスプロセスを定義します。この例では、新規の Case が作成または更新されるたびにタスクを作成するために、レコードトリガー型フロー を使用する方法を示します。

  1. [設定] で「フロー」を検索して選択します。

  2. [新規フロー] をクリックし、[レコードトリガー型フロー] を選択します。

  3. トリガーを設定します:
    • オブジェクト:Case
    • フローをトリガーするタイミング: レコードが作成されたとき
    • フローの最適化対象: アクションおよび関連レコード

  4. [完了] をクリックします。

  5. フローキャンバスで、+ アイコンをクリックし、「アクション」エレメントを選択します。

  6. 「アクション」検索ボックスで、「Apex」カテゴリーを選択し、「Queue Bright Pattern Task」を選択します。

  7. アクションの詳細を入力します。
    • ラベル:アクションに、Create BP Task for New Caseのような、わかりやすい名前を付けます。
    • 入力値のマッピング:トリガーとなる Case レコード($Record)のフィールドを、Apex アクションの入力にマッピングします。
      • Case ID for Screenpop:$Record.Id
      • Contact ID:$Record.ContactId
      • Case Number:$Record.CaseNumber
      • Task Subject:$Record.Subject
      • Task Priority:必要に応じて、オプションで、キュー優先度 を設定して、タスクシナリオエントリーで設定された優先度を上書きするために、

  8. [完了] をクリックします。

  9. [保存] をクリックし、フローに名前を付け(例:New Case to Bright Pattern Task)、[有効化] をクリックします。

  10. 新規レコードが作成されると、エージェントデスクトップにタスクが自動的にキューに入れられます。
    < 前へ