# Preview Dialer for Outbound Campaigns (Flex UI 1.x.x)

> \[!NOTE]
>
> This guide is only for Flex UI 1.x.x, which [reached End of Life on June 30, 2024](/docs/flex/flex-ui-eol-reference). To build on a current version, we recommend you [upgrade to Flex UI 2.x.x](/docs/flex/developer/ui/migration-guide).

## Overview

> \[!WARNING]
>
> This solution features sample code that is provided "as is" and is not production grade. The featured code does not account for edge case handling, scalability, and reliability. It is not covered under Twilio's [Service Level Agreement (SLA)](https://www.twilio.com/en-us/legal/service-level-agreement) and [support plans](https://www.twilio.com/en-us/support-plans).

The Flex Preview Dialer for Outbound Campaigns solution helps call center administrators automate and manage outbound campaigns using the Twilio platform. An administrator can use a JSON file to define an array of outbound campaigns and each campaign's schedule.

The solution provides the following functionalities:

* Import a CSV of contacts (name and phone number) and associate them with an outbound campaign
* Schedule outbound campaigns to happen immediately or at the day and time intervals that you specify
* Define a set of campaigns in a JSON file that gets rendered as a dropdown list

## Architecture

![Flowchart showing preview dialer process with icons for tasks, agents, and call distribution.](https://docs-resources.prod.twilio.com/586e8300a45a08e82b557c052eeaf8128d747cef2e8d935206d620c734d3fd66.png)

This solution leverages the Flex Preview Dialer plugin which uses [Twilio Functions](/docs/serverless/api) and the [Actions Framework StartOutboundCall action](/docs/flex/developer/ui/v1/actions) to create tasks in Twilio TaskRouter. TaskRouter in turn routes the preview dialing tasks to the available agents on the queue(s) you've selected for your outbound campaign. When an agent accepts a preview task, Flex initiates an outbound call (represented as a voice task) to the number on that contact and automatically connects it to *that* same agent.

## Prerequisites

To deploy this solution, you will need:

* An active Twilio account with Flex provisioned. Refer to the [Flex Basics Quickstart](/docs/flex/admin-guide/setup/account-creation) to create one.
* npm version 6.0.0 installed (type `npm -v` in your terminal to check)
* A Node.js [long-term-support (LTS) version](https://nodejs.org/en/about/releases/) installed, 14 recommended (type `node -v` in your terminal to check)
* [Native Dialpad configured on your Flex instance](/docs/flex/admin-guide/setup/voice/dialpad/enable)
* Outbound campaigns and contacts list you want to leverage for this solution (the solution includes CSV upload and scheduling components for demonstration purposes)
* [Twilio CLI](/docs/twilio-cli/quickstart#install-the-twilio-cli) along with the Flex CLI Plugin and the [Serverless Plugin](/docs/twilio-cli/plugins#available-plugins). Run the following commands to install them:

  ```bash
  # Install the Twilio CLI
  npm install twilio-cli@2.0 -g
  # Install the Serverless and Flex as Plugins
  twilio plugins:install @twilio-labs/plugin-serverless@latest
  twilio plugins:install @twilio-labs/plugin-flex
  ```

> \[!NOTE]
>
> If you're running Linux, click on the Linux tab for the [Twilio CLI installation instructions](/docs/twilio-cli/quickstart#install-the-twilio-cli). If you're running Windows, make sure to run the Windows command prompt as an administrator to install the Serverles/Flex plugins for the Twilio CLI. The Windows commands in this guide use PowerShell (for Node.js/npm installation).

## Deployment Time

30 minutes

## Tested Flex Versions

* Flex v1.18.1-1.24.3
* macOS / Unix
* Windows 10

## Configure your Flex Workspace

In order to use the solution, you need to prepare your **Flex Task Assignment** workspace.

### Retrieve your Flex settings

#### Step 1

Navigate to your Flex project in the [Twilio Console](https://www.twilio.com/console). Copy your **ACCOUNT SID** and **AUTH TOKEN**, and create a new Twilio CLI profile using those credentials:

```bash
twilio profiles:create
```

You will be prompted to enter your Twilio Account SID, Auth Token, and a shorthand identifier for your profile. When choosing a shorthand identifier, pick one that is meaningful and that you can remember. Once your profile has been created, activate it by running:

```bash
twilio profiles:use PROFILE_ID
```

Keep in mind that this account will be used for the rest of the deployment. In order to switch accounts, use the following command:

```bash
twilio profiles:use DIFFERENT_PROFILE_ID
```

### Step 2

Retrieve your Flex Task Assignment workspace SID:

```bash
twilio api:taskrouter:v1:workspaces:list
```

**Example Workspace SID**

```bash
SID                                 Friendly Name        Prioritize Queue Order
WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  Flex Task Assignment FIFO

```

### Step 3

Create a task channel for the preview dialing tasks using your Flex workspace SID that you copied in the previous step. This task channel will be used for routing preview dialing tasks to available agents.

```bash
twilio api:taskrouter:v1:workspaces:task-channels:create --friendly-name "preview-dialer" --unique-name "previewdialer" --workspace-sid WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```

**Example API Response**

```bash
SID                                  Friendly Name   Date Created
TCXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX   preview-dialer  Jun 22 2020 22:06:27 GMT-0700

```

### Step 4

Create a workflow filter to accommodate the preview tasks and scheduling for your outbound campaign. In this guide, we will modify the "Assign To Anyone" workflow. Run the following to retrieve your workflow SID:

```bash
twilio api:taskrouter:v1:workspaces:workflows:list --friendly-name="Assign to Anyone" --workspace-sid WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```

Next, run the following to retrieve your queue SID:

```bash
twilio api:taskrouter:v1:workspaces:task-queues:list --workspace-sid WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
```

Before running the next command, make the following changes:

* Update the **"queue"** fields in the JSON configuration with your target and default queue SIDs
* Update **"--sid"** in the API request to the workflow SID that you retrieved previously
* Update **"--workspace-sid"** with the SID of your **Flex Task Assignment** workspace.

## macOS/Linux

```bash
CONFIGURATION=$(cat << EOF
{
  "task_routing": {
    "filters": [
      {
        "filter_friendly_name": "Preview Dialer",
        "expression": "type = \"preview-dialer\"",
        "targets": [
          {
            "queue": "WQYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY",
            "expression": "(taskrouter.dayOfWeek IN task.schedule.week) AND (taskrouter.currentTime > task.schedule.startHour) AND\n(taskrouter.currentTime < task.schedule.endHour)"
          }
        ]
      }
    ],
    "default_filter": {
      "queue": "WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
    }
  }
}
EOF
)

twilio api:taskrouter:v1:workspaces:workflows:update --sid="" --workspace-sid="WSXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" --configuration "$CONFIGURATION"

```

## Windows

First, set your required Queue SIDs, your Flex workspace SID, and your "Assign to Anyone" workflow SID as environment variables.

```bash
set QUEUESID1=WQXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
set EVERYONEQUEUE=WQYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
set WORKSPACESID=WSYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY
set WORKFLOWSID=WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

```

To confirm that an environment variable has been set, run `echo %<ENVVAR>%`.

```bash
twilio api:taskrouter:v1:workspaces:workflows:update --sid=%WORKFLOWSID% --workspace-sid=%WORKSPACESID% --configuration="{ ""task_routing"": { ""filters"": [{ ""filter_friendly_name"": ""Preview Dialer"", ""expression"": ""type = 'preview-dialer'"", ""targets"": [{""queue"": ""%QUEUESID1%"", ""expression"": ""(taskrouter.dayOfWeek IN task.schedule.week) AND (taskrouter.currentTime > task.schedule.startHour) AND\n(taskrouter.currentTime < task.schedule.endHour)"" }]}], ""default_filter"": { ""queue"": ""%EVERYONEQUEUE%""}}}"
```

**Example API Response**

```bash
SID                                 Friendly Name     Document Content Type
WWXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX  Assign to Anyone  null

```

To learn about configuring more complex workflows, see [Create a Workflow Resource](/docs/taskrouter/api/workflow#create-a-workflow-resource) and [Configuring Workflows: Complex Routing Example](/docs/taskrouter/workflow-configuration).

## Download the Flex Preview Dialer Plugin

Download the [plugin source code](https://github.com/twilio-professional-services/flex-preview-dialer/archive/refs/heads/main.zip) and unzip the files in a local directory. Open a terminal or command shell session.

## Deploy your Twilio Function

We will deploy the Preview Dialer function to your Flex instance. The function is called from the plugin you will deploy in the next step and integrates with TaskRouter, passing in required attributes to generate the preview dialing task, and the subsequent voice task which is routed to the agent who accepted the preview task.

**Step 1:** Change into the `serverless` directory and rename `.env.example`.

## macOS/Linux

```bash
flex-preview-dialer $ cd serverless && mv .env.example .env
```

## Windows

```bash
C:\Users\username\flex-preview-dialer-master>cd serverless && move .env.example .env
```

**Output**

```bash
1 file(s) moved.
```

**Step 2:** Open `.env` and set the environment variables mentioned in the file.

ACCOUNT\_SID = your Account SID from twil.io/console AUTH\_TOKEN = your Auth Token from twil.io/console PREVIEW\_DIALER\_WORKFLOW\_SID = your Flex preview dialer workflow ID TWILIO\_WORKSPACE\_SID = your Flex Task Assignment workspace ID PREVIEW\_DIALER\_TASK\_CHANNEL\_SID = your Flex task channel ID\
**Step 3:** Run the following to install the Function dependencies:

```bash
serverless $ npm install
```

**Step 4:** Deploy the Twilio function to your account using the Twilio CLI:

```bash
twilio serverless:deploy

```

> \[!NOTE]
>
> When running on Windows, you may see an error with the Twilio Serverless deployment command. To work around the issue, set your `TWILIO_ACCOUNT_SID` and `TWILIO_AUTH_TOKEN` as environment variables. Refer to the previous section for examples of how to set an environment variable in Windows.

### Example Function Deployment Output

```bash
 Deploying functions & assets to the Twilio Runtime
✔ Serverless project successfully deployed

Deployment Details
Domain: flex-preview-dialer-xxxx-dev.twil.io
Service:
   flex-preview-dialer (ZSxxxx)
...

```

**Step 5:** Copy and save the domain returned when you deploy a function. You will need it in the next step.

If you forget to copy the domain, you can also refer to it by navigating to [Functions > API](https://www.twilio.com/console/functions/api).

**Debugging Tip:** Pass the `-l` or logging flag to review deployment logs. For example, you can pass `-l debug` to turn on debugging logs.

## Deploy your Flex Plugin

Once you have deployed the function, it is time to deploy the plugin to your Flex instance.

First, rename `.env.example` to `.env`.

## macOS/Linux

```bash
flex-preview-dialer $ mv .env.example .env
```

## Windows

```bash
C:\Users\username\flex-preview-dialer-master>move .env.example .env
```

**Output**

```bash
1 file(s) moved.
```

Open `.env` in a text editor of your choice. Modify the `REACT_APP_SERVICE_BASE_URL` property to the Domain name you copied in the previous step. Make sure to prefix it with "https://".

```bash
 // .env
REACT_APP_SERVICE_BASE_URL=https://flex-preview-dialer-xxxx-dev.twil.io

```

When you are ready to deploy the plugin, run the following in a command shell:

```bash
twilio flex:plugins:deploy --major --changelog "Preview Dialer Plugin" --description "Preview Dialer for Outbound Campaigns plugin"

```

### Example Plugin Deployment Output

```bash
✔ Validating deployment of plugin flex-preview-dialer
⠧ Compiling a production build of flex-preview-dialerPlugin flex-preview-dialer was successfully compiled with some warnings.
✔ Compiling a production build of flex-preview-dialer
✔ Uploading flex-preview-dialer
✔ Registering plugin flex-preview-dialer with Plugins API
✔ Registering version v1.0.0 with Plugins API

🚀 Plugin (private) flex-preview-dialer@1.0.0 was successfully deployed using Plugins API

Next Steps:
Run $ twilio flex:plugins:release --plugin flex-preview-dialer@1.0.0 --name "Autogenerated Release 1602189036080" --description "The description of this Flex Plugin Configuration" to enable this plugin on your Flex application
```

### Enable Plugin on your Flex application

The step above only deploys your Plugin, you still need to enable the Plugin on your Flex application. Run the following command to enable it on Flex.

```bash
 twilio flex:plugins:release --plugin flex-preview-dialer@1.0.0 --name "Preview Dialer for Outbound Campaigns" --description "Enabling preview dialer using Solution Guide"
```

### View plugin on the Plugins Dashboard

After running the suggested next step, navigate to the [Plugins Dashboard](https://flex.twilio.com/admin/) to review your recently deployed plugin and confirm that it's enabled for your contact center.

You are all set to test the Preview Dialer for Outbound Campaigns on your Flex application!

> \[!WARNING]
>
> Keep in mind that your Agents need to refresh their browsers in order to get the latest changes.

## Testing the solution

**Step 1:** Log in as an `admin` to your [Flex instance](https://flex.twilio.com/) where you deployed the plugin.

**Step 2:** Change your status to **Available** on the upper right corner of the Flex UI. This enables you to receive incoming calls and messages (SMS or chat).

**Step 3:** With your specific campaign selected from the Campaigns dropdown list, import a CSV file of Contacts. You can have two columns: Contact Name, and Destination (Phone Number). For example:

```bash
$ cat contacts.csv
name,destination
Alice,1234567890

```

***You do not need to include your country code in the destination numbers.* Step 4:** To generate a preview task for each contact in the list:

* Click "Call Now" to generate preview tasks for your campaign immediately.
* Click "Schedule" to set up scheduling for your selected campaign. When specifying a schedule, note that the TaskRouter API utilizes Coordinated Universal Time (UTC).

**Step 5:** To see the incoming preview tasks (displayed with the Campaign name and the phrase "Call to ", navigate to the [Agent Desktop](https://flex.twilio.com/agent-desktop) in your Flex Instance.

**Step 6:** Upon clicking "Accept", you should see a connecting call to the destination number (which has been added as an attribute on the subsequent "voice" task).

![Twilio Flex interface showing call details with task context and customer phone number.](https://docs-resources.prod.twilio.com/70db9cd30cc3961bf94b57041ae24d2e1b3d63dce7d8191272927131fdd76944.png)

**Tip:** You can review the tasks that get generated after acceptance of the preview task by running

```bash
twilio api:taskrouter:v1:workspaces:tasks:list --workspace-sid <flex_task-assignment_sid>
```
