

# Amazon Connect Cases event streams
<a name="case-event-streams"></a>

Amazon Connect Cases event streams provide you with near real-time updates when cases are created or modified within your Amazon Connect Cases domain. The events published to the stream include these resource events:
+ Case created
+ Cases modified
+ Related items (Comments, Calls, Chats, Tasks) are added to a case

You can use the case event streams to integrate streams into your data lake solutions, create dashboards that display case performance metrics, implement business rules or automated actions based on case events, and configure alerting tools to trigger custom notifications of specific case activity.

**Topics**
+ [Set up case event streams](case-event-streams-enable.md)
+ [Allow Cases to send updates to Contact Lens rules](cases-rules-integration-onboarding.md)
+ [Case event payload and schema](case-event-streams-sample.md)

# Set up Amazon Connect Cases event streams
<a name="case-event-streams-enable"></a>

This topic explains how to set up and use case event streams. Some of the onboarding steps require you to call [Amazon Connect Cases APIs](https://docs.aws.amazon.com/cases/latest/APIReference/Welcome.html).

## Step 1: Create an Amazon Connect instance and enable Customer Profiles
<a name="step1-case-event-streams-enable"></a>

1. Ensure you have an working Amazon Connect instance in one of the AWS Regions where Cases is available. See [Cases availability by Region](regions.md#cases_region).

1. Enable Amazon Connect Customer Profiles. For instructions, see [Enable Customer Profiles for your Amazon Connect instance](enable-customer-profiles.md).

   Amazon Connect Cases requires Customer Profiles because each case must be associated with a customer profile from the Customer Profiles service.

## Step 2: Add a Cases domain to your Amazon Connect instance
<a name="step2-case-event-streams-enable"></a>

For instructions, see [Enable Cases using the Amazon Connect console](enable-cases.md).

If you want to add a case domain using the API, see the [CreateDomain](https://docs.aws.amazon.com/cases/latest/APIReference/API_CreateDomain.html) API in the *Amazon Connect Cases API Reference*. 

## Step 3: Create a case template
<a name="step3-case-event-streams-enable"></a>

[Create a case template](case-templates.md). In *Step 6: Test case event streams*, you'll use the template. 

If you want to create a case template using the API, see the [CreateTemplate](https://docs.aws.amazon.com/cases/latest/APIReference/API_CreateTemplate.html) API in the *Amazon Connect Cases API Reference*. 

## Step 4: Enable case event streams and setup to receive events into an SQS queue
<a name="step4-case-event-streams-enable"></a>

Run the following command to enable case event streams for your Cases domain. After this command runs, when cases are created or updated, an event is published to the default-bus of the EventBridge service in your account (it must be in the same AWS Region as your Cases domain).

```
aws connectcases put-case-event-configuration --domain-id dad5efb6-8485-4a55-8241-98a88EXAMPLE --event-bridge enabled=true
```

By default, the events published by Amazon Connect Cases only contain metadata about the case, such as `templateId`, `caseId`, `caseArn`, `approximateChangeTime`, and more. You can run the following command to get more information about the case (at the time the event was generated) to be included in the event.

**Note**  
If you want to include a custom field in the event, use the custom field ID. For instructions about how to locate the custom field ID, see [Find the custom field ID](cases-block.md#get-case-properties-find-uuid). 

```
# You can include any other field defined in your cases domain in the fields section.
# To list the fields that are defined in your cases domain, call the Cases ListFields API.
# To include case fields that you create (custom fields) in the event, enter the custom field ID.
aws connectcases put-case-event-configuration --domain-id YOUR_CASES_DOMAIN_ID --event-bridge "{
    \"enabled\": true, 
    \"includedData\": {
       \"caseData\": {
          \"fields\": [
          {
          \"id\": \"status\"
          },
          {
          \"id\": \"title\"
          },
          {
          \"id\": \"customer_id\"
          },
         {
          \"id\": \"your custom field ID\"
          }
        ]
      },
      \"relatedItemData\": {
      \"includeContent\": true
      }
    }
  }"
```

Next, create an Amazon SQS queue and set that as a target for the Amazon Connect Cases events on your EventBridge bus so that all the case events are delivered to the SQS queue for later processing.

```
# Create an SQS queue
aws sqs create-queue --queue-name case-events-queue --attributes "{\"Policy\": \"{ \\\"Version\\\": \\\"2012-10-17\\\", \\\"Statement\\\": [{ \\\"Sid\\\": \\\"case-event-subscription\\\", \\\"Effect\\\": \\\"Allow\\\", \\\"Principal\\\": { \\\"Service\\\": \\\"events.amazonaws.com\\\"}, \\\"Action\\\": \\\"SQS:SendMessage\\\", \\\"Resource\\\": \\\"*\\\"}]}\"}"

# Create an rule on the EventBridge default bus that represents the case events
aws events put-rule --name case-events-to-sqs-queue --event-pattern "{\"source\": [\"aws.cases\"]}" --state ENABLED

# Ask event bridge to publish case events to the SQS queue.
aws events put-targets --rule case-events-to-sqs-queue --target "[{
\"Id\": \"target-1\",
\"Arn\": \"arn:aws:sqs:The AWS Region of your Amazon Connect instance:your AWS account ID:case-events-queue\"
}]"
```

## Step 5: Test case event streams
<a name="step5-case-event-streams-enable"></a>

Use the Amazon Connect agent application to: 

1. Accept a chat contact.

1. Create a customer profile and associate that to the chat contact.

1. Create a case. 
**Note**  
The **Create case** button on the **Cases** tab is inactive until you accept a contact and associate that contact with a customer profile.

Navigate to the Amazon SQS console and check that a case event (type: `CASE.CREATED`) for the newly created case is available in your SQS Queue. Similarly, you can modify the case created above and get a corresponding case event (type: `CASE.UPDATED`) in your SQS queue. You can associate the contact to the case, and leave a comment on the case to get case events for those actions, too.

## Step 6: Use cases for the case event streams
<a name="step6-case-event-streams-enable"></a>

Case event streams publish events every time a case is created, case is updated, contact is associated to the case, and comment is added on a case. You can use these events for:
+ Metrics, analytics and dashboards
+ Build Apps that notify users (for example, send emails)
+ Automated actions that are triggered based on certain type of case updates

For example, you can use the SQS target on EventBridge (as shown on step 4) to temporarily store the case events in the SQS queue, and use Lambda functions to process events in the SQS to build custom applications such as sending emails to the customer when their case is updated, automatically resolving any tasks linked to the case, and more. Similarly, you can use the Firehose target on the EventBridge to store the case events into an S3 bucket and then use the AWS Glue for ETL, Athena for ad-hoc analytics, and Quick for dashboards.

# Allow Amazon Connect Cases to send updates to Contact Lens rules
<a name="cases-rules-integration-onboarding"></a>

**Note**  
To perform the instructions in this procedure, you need to have developer skills, or be experienced with Amazon Connect CLI.

Complete this one-time procedure so your users can set up rules that run when a case is created or updated. 

1. Verify Amazon Connect Cases is [enabled](enable-cases.md) for your Amazon Connect instance. 

1. Complete the steps to enable Amazon Connect Cases event streams. For more information see [Set up Amazon Connect Cases event streams](case-event-streams-enable.md). Note the following changes to the procedure:

   1. You can skip the part that asks you to create a SQS queue, as it is not required.

   1. Run the `put-case-event-configuration` CLI command to include all case fields information in the event. Make sure to include all of the fields that you need for the Rules engine to work.
**Note**  
To ensure that Cases SLA Breach rules work properly, you must set `relatedItemData.includeContent` to `true`, as shown in the following example.

      ```
      aws connectcases put-case-event-configuration --domain-id 01310a0e-24ba-4a3c-89e9-9e1daeaxxxx --event-bridge "{
          \"enabled\": true, 
          \"includedData\": {
             \"caseData\": {
                 \"fields\": [
                   {
                     \"id\": \"status\"
                   },
                   {
                     \"id\": \"title\"
                   },
                   {
                     \"id\": \"assigned_queue\"
                   },
                   {
                     \"id\": \"assigned_user\"
                   },
                   {
                     \"id\": \"case_reason\"
                   },
                   {
                     \"id\": \"last_closed_datetime\"
                   },
                   {
                     \"id\": \"created_datetime\"
                   },
                   {
                     \"id\": \"last_updated_datetime\"
                   },
                   {
                     \"id\": \"reference_number\"
                   },
                   {
                     \"id\": \"summary\"
                   }
                 ]
            },
            \"relatedItemData\": {
            \"includeContent\": true
            }
          }
        }"
      ```

   1. If there are custom case fields, make sure to include a custom field ID the fields array in the previous payload as well. You can find field IDs by running the following `list-fields` CLI command:

      ```
      aws connectcases list-fields --domain-id 01310a0e-24ba-4a3c-89e9-9e1daeaxxxx
      ```

   1. Repeat step 2 if you need to add new custom fields. 

1. Make a [CreateEventIntegration](https://docs.aws.amazon.com/appintegrations/latest/APIReference/API_CreateEventIntegration.html) API call, or run the `create-event-integration` CLI command, as shown in the following example command.
   + Payload:

     ```
     aws appintegrations create-event-integration --name amazon-connect-cases --description amazon-connect-cases --event-filter '{"Source":"aws.cases"}' --event-bridge-bus default
     ```
   + The output will look similar to the following sample:

     ```
     {
         "EventIntegrationArn": "arn:aws:app-integrations:us-west-2:111222333444:event-integration/amazon-connect-cases"
     }
     ```

1. Make a [CreateIntegrationAssociation](https://docs.aws.amazon.com/connect/latest/APIReference/API_CreateIntegrationAssociation.html) API call, or run the `create-integration-association` CLI command, as shown in the following example command.
   + Payload:

     The `IntegrationArn` is the response you get from step 3.

     ```
     aws connect create-integration-association --instance-id bba5df5c-6a5f-421f-a81d-9c16402xxxx --integration-type EVENT --integration-arn arn:aws:app-integrations:us-west-2:111222333444:event-integration/amazon-connect-cases --source-type CASES
     ```
   + The output will be similar to the following sample:

     ```
     {
         "IntegrationAssociationId": "d49048cd-497d-4257-ab5c-8de797a123445",
         "IntegrationAssociationArn": "arn:aws:connect:us-west-2:111222333444:instance/bba5df5c-6a5f-421f-a81d-9c16402bxxxx/integration-association/d49048cd-497d-4257-ab5c-8de797a123445"
     }
     ```

Your users should now be able to create rules that run when a case is created or updated.

# Case event payload and schema in Amazon Connect Cases
<a name="case-event-streams-sample"></a>

When you request to include case data in the event payload, the data reflects the version of the case after that particular edit. 

Amazon Connect Cases default limits guarantee that the payload will be less than 256KB (the maximum size of an EventBus event). Since you can customize the case object model (for example, you can define custom fields on case objects to capture business specific information), case event schema reflect the customizations made to the case object as shown in the following examples (for example, see how customer-specific UUIDs are being use as JSON properties). 

## Example case event payload for the case resource
<a name="example-case-event-payload"></a>

```
// Given the limits on the "includedData" configuration
// this payload is guaranteed to less than 256KB at launch.
{
    "version": "0",
    "id": "event ID",
    "detail-type": "Amazon Connect Cases Change",
    "source": "aws.cases",
    "account": "your AWS account ID",
    "time": "2022-03-16T23:43:26Z",
    "region": "The AWS Region of your Amazon Connect instance",
    "resources": [
        "arn:aws:cases:your Amazon Connect AWS Region:your AWS account ID:domain/case domain ID",
        "arn:aws:cases:your Amazon Connect AWS Region:your AWS account ID:domain/case domain ID/case/case ID"
    ],
    "detail": {
        "version": "0",
        "eventType": "CASE.UPDATED",
        "approximateChangeTime": "2022-03-16T23:16:57.893Z",  // Can be used for ordering
        "changedFieldIds": ["status", "last_updated_datetime"],
        "performedBy": {
            "user": {
                "userArn": "arn:aws:connect:your Amazon Connect AWS Region:your AWS account ID:instance/connect instance ID/user/connect user ID"        
            },
            "iamPrincipalArn": "arn:aws:iam::your Amazon Connect AWS Region:role/role name"
        },       
        "case": {
            "caseId": "case ID",
            "templateId": "template ID",
            "createdDateTime": "2022-03-16T23:16:57.893Z",
            
            // This section contains only non-null field values for the 
            // fields that customers have configured in the "includedData".
           
            // Field values included in this section reflects the case
            // after this particular change is applied.
            "fields": {
                "status": {
                    "value": {
                        "stringValue": "open"
                   }
                },
                "case_reason": {
                    "value": {
                        "stringValue": "Shipment lost"
                    }
                },
                "custom-field-uuid-1": {
                    "value": {
                        "stringValue": "Customer didn't receive the product"
                    }
                }
            }
        }
    }
}
```

## Example case event payload for the related-item resource
<a name="example-case-event-payload"></a>

```
// Given the limits on the "includedData" configuration
// this payload is guaranteed to less than 256KB
{
    "version": "0",
    "id": "event ID",
    "detail-type": "Amazon Connect Cases Change",
    "source": "aws.cases",
    "account": "your AWS account ID",
    "time": "2022-03-16T23:43:26Z",
    "region": "The AWS Region of your Amazon Connect instance",
    "resources": [
        "arn:aws:cases:your Amazon Connect AWS Region:your AWS account ID:domain/case domain ID",
        "arn:aws:cases:your Amazon Connect AWS Region:your AWS account ID:domain/case domain ID/case/case ID/related-item/related-item ID"
    ],
    
    "detail": {   
        "version": "0",
        "eventType": "RELATED_ITEM.CREATED",
        "approximateChangeTime": "2022-03-16T23:16:57.893Z", // Can be used for ordering
        "changedAttributes": ["comment.commentText"],
        "performedBy": {
            "user": {
                "userArn": "arn:aws:connect:your Amazon Connect AWS Region:your AWS account ID:instance/connect instance ID/user/connect user ID"        
            },
            "iamPrincipalArn": "arn:aws:iam::your Amazon Connect AWS Region:role/role name"
        },        
        "relatedItem": {
            "relatedItemType": "Comment",
            "relatedItemId": "related-item ID",
            "caseId": "case id that this related item is a sub-resource of",
            "createdDateTime": "2022-03-16T23:16:57.893Z",
            
            // This section includes any attributes that customers have configured
            // in the "includedData" configuration.
            "comment": {               
                "body": "Gave a $5 refund to customer to make them happy",
            },
            
            // if the related item was of type contact.
            // "contact": {
            //      "contactArn": ".......",
            // }
        }
    }
}
```

## Example case event payload for the case resource performed by custom entity
<a name="example-case-event-payload-case-resource-custom-entity"></a>

```
// Given the limits on the "includedData" configuration
// this payload is guaranteed to less than 256KB at launch.
{
    "version": "0",
    "id": "event ID",
    "detail-type": "Amazon Connect Cases Change",
    "source": "aws.cases",
    "account": "your AWS account ID",
    "time": "2022-03-16T23:43:26Z",
    "region": "The AWS Region of your Amazon Connect instance",
    "resources": [
        "arn:aws:cases:your Amazon Connect AWS Region:your AWS account ID:domain/case domain ID",
        "arn:aws:cases:your Amazon Connect AWS Region:your AWS account ID:domain/case domain ID/case/case ID"
    ],
    "detail": {
        "version": "0",
        "eventType": "CASE.UPDATED",
        "approximateChangeTime": "2022-03-16T23:16:57.893Z",  // Can be used for ordering
        "changedFieldIds": ["status", "last_updated_datetime"],
        "performedBy": {
            "user": {
                "customEntity": "your custom entity"        
            },
            "iamPrincipalArn": "arn:aws:iam::your Amazon Connect AWS Region:role/role name"
        },       
        "case": {
            "caseId": "case ID",
            "templateId": "template ID",
            "createdDateTime": "2022-03-16T23:16:57.893Z",
            
            // This section contains only non-null field values for the 
            // fields that customers have configured in the "includedData".
           
            // Field values included in this section reflects the case
            // after this particular change is applied.
            "fields": {
                "status": {
                    "value": {
                        "stringValue": "open"
                   }
                },
                "case_reason": {
                    "value": {
                        "stringValue": "Shipment lost"
                    }
                },
                "custom-field-uuid-1": {
                    "value": {
                        "stringValue": "Customer didn't receive the product"
                    }
                }
            }
        }
    }
}
```