# Variables

## Integration <a href="#integration" id="integration"></a>

### Add note script <a href="#add-note-script" id="add-note-script"></a>

The Add Note Script is used to notify the end user about integration events. These notes are automatically added during processing and the script allows the target of the note to be customised. E.g., notes are usually added to work notes on Task-based tables, but a custom table might have a different field for this.

```javascript
// An example add note script
function addNote(target, note, options) {
  var message = '[' + options.integration_name + ' Integration] ' + note;
  if (options.type == 'error' || options.type == 'warn') {
    message = '[code]<span style="color: red">' + message + '</span>[/code]';
  }
  target.work_notes = message;
}
```

| Variable                    | Type        | Description                                                                                                                                                |
| --------------------------- | ----------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `target`                    | GlideRecord | The target record to update, e.g. an Incident record.                                                                                                      |
| `note`                      | String      | The update message.                                                                                                                                        |
| `options`                   | Object      | An object containing specific properties depending on the note being added.                                                                                |
| `options.integration_name`  | String      | The name of the integration.                                                                                                                               |
| `[options.response_action]` | GlideRecord | <p>The <code>Response Action \[x\_snd\_eb\_response\_action]</code> record being used.</p><p><em>Only provided with response action notification.</em></p> |
| `[options.type]`            | String      | <p>The type of note: <code>info</code> or <code>error</code>.</p><p><em>Only provided with Bond specific notes.</em> </p>                                  |
| `variables`                 | Object      | Object used to contain Connection Variables.                                                                                                               |
| `log`                       | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                     |
| `error`                     | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.                 |

### Identify message script <a href="#identify-message-script" id="identify-message-script"></a>

The Identify Message Script is executed when an inbound request is received. It returns the name of the message that should be used to process the request. Typically, message names are embedded within the request payload, but it's possible to use the other variables available for more complex identification.

```javascript
// An example identify script
function identify() {
  return (payload.message.name || '') + '';
}
```

| Variable      | Type        | Description                                                                                                                                           |
| ------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payload`     | Any         | The payload string or object. Pre-processing can be configured on the Integration to automatically convert JSON to `Object` or XML to `XMLDocument2`. |
| `headers`     | Object      | An object containing the request headers.                                                                                                             |
| `params`      | Object      | A key-value pair object of URL parameters.                                                                                                            |
| `integration` | GlideRecord | The `Integration [x_snd_eb_integration]` record.                                                                                                      |
| `connection`  | GlideRecord | The `Connection [x_snd_eb_connection]` record used to receive the request.                                                                            |
| `variables`   | Object      | Object used to contain Connection Variables.                                                                                                          |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.            |

## Connection <a href="#connection" id="connection"></a>

### Endpoint URL <a href="#endpoint-url" id="endpoint-url"></a>

The Endpoint URL will be prepended to Message Path values (providing they do not override). Inline scripts using curly braces `{}` can be used to construct more advanced endpoints.

{% hint style="info" %}
See [Message Path](#path) parameters for available variables.
{% endhint %}

{% hint style="warning" %}
We recommend dynamic endpoints only be considered for the same environment. New environments should have new connections so they can be managed more easily.
{% endhint %}

## Message <a href="#message" id="message"></a>

### Advanced condition

The Advanced condition is used to script complex trigger logic into the message. Only use this if you cannot use the Outbound condition filters and the single line Outbound condition.

{% hint style="info" %}
See [Outbound condition](#outbound-condition) parameters for available variables.
{% endhint %}

### Extract attachments script

Attachments can be extracted from payloads and saved before the payload is saved. This is highly recommended as it saves from storing the attachment itself in the payload on the HTTP Request record.

Attachment data should be extracted, saved as an attachment, and replaced with the attachment sys\_id in the format `<x-attachment-data sys_id="...">`. Unifi will automatically collect the attachment ids, create Bonded Attachments for each of them, and finally move the attachments to the target record.

{% hint style="info" %}
Streaming is better. Attachments can be streamed into Unifi which bypasses the need for extraction, supports binary file sharing, and also allows for sizes up to 50MB (providing your instance and integration configuration supports this).

This is available for all new integrations from Unifi 3.0. Contact us for information on how to do this with previous versions.
{% endhint %}

{% tabs %}
{% tab title="Extract attachments script" %}

```javascript
// Example extract attachments script using a Script Include
// for extracting Base64 from an XML payload.
// We rewrite the payload to pass back to Unifi
payload = unifi_util.extractAttachmentsFromXml(payload, request);
```

{% endtab %}

{% tab title="Script Include" %}

```javascript
// Example script include extract for extracting Base64 attachment
// data from an XML payload.
// To be used with a Unifi Extract attachments script.
unifi_util.extractAttachmentsFromXml = function extractAttachmentsFromXml(payload, request) {

  // create a new standard XMLDocument so we can rewrite it on the fly
  var xml_doc = new XMLDocument(payload.toString()),
      attachment_container;

  function extract(node) {
    var result = null,
        name,
        tag;

    if (node.getNodeName() == 'eb:Attachment') {
      result = {};
      forEachNode(node.getChildNodes(), function (attr) {
        // convert eb:FileName to FileName
        var name = attr.getNodeName().split(':').pop();
        if (name == '#text') return;
        result[name] = '' + attr.getTextContent();
        if (name == 'Data') {
          attr.setTextContent(''); // remove the attachment data
        }
      });

      // Write the attachment using internal Unifi util
      //tag = '<x-attachment-data sys_id="abc123" />';
      tag = x_snd_eb.AttachmentHandler.saveAttachment(
        request, result.FileName, result.MimeCode, decodeData(result.Data));

      insertPointer(node, tag);
    }
  }

  function insertPointer(node, tag) {
    var id,
        data;
    // add the attachment pointer for the processor to pick up
    data = node.getElementsByTagName('eb:Data');
    if (data.getLength() &gt; 0) {
      xml_doc.setCurrent(data.item(0));
      xml_doc.setCurrent(xml_doc.createElement('x-attachment-data'));
      id = tag.match(/sys_id="(.+)"/);
      xml_doc.setAttribute('sys_id', id ? id[1] : 'unknown');
    }
  }

  function forEachNode(node_list, fn) {
    var len = node_list.getLength(),
        i;
    for (i = 0; i &lt; len; i++) {
      fn(node_list.item(i), i);
    }
  }

  function decodeData(data) {
    data = ('' + data).replace(/\s/g, '');
    if (global.snd_eb_util &amp;&amp; global.snd_eb_util.writeAttachment) {
      return GlideStringUtil.base64DecodeAsBytes(data);
    } else {
      return GlideStringUtil.base64Decode(data);
    }
  }

  attachment_container = xml_doc.getElementByTagName('eb:Attachments');
  if (attachment_container) {
    forEachNode(attachment_container.getChildNodes(), extract);
  }

  return xml_doc.toString();
};
```

{% endtab %}

{% tab title="XML" %}

```markup
<!-- Example attachments payload structure -->
<eb:Attachments xmlns:eb="https://sharelogic.com/unifi">
    <eb:Attachment>
      <eb:FileName>Hello world.txt</eb:FileName>
      <eb:MimeCode>text/plain</eb:MimeCode>
      <eb:Data>SGVsbG8gd29ybGQudHh0</eb:Data>
    </eb:Attachment>
</eb:Attachments>
```

{% endtab %}
{% endtabs %}

| Variable            | Type           | Description                                                                                                                                                        |
| ------------------- | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `payload`           | String\|Stream | The raw inbound payload object to process. Attachment data should be removed and replaced with the attachment sys\_id in the format "\<x-attachment-data sys\_id=> |
| `headers`           | Object         | An object containing the request headers.                                                                                                                          |
| `params`            | Object         | A key-value pair object of URL parameters.                                                                                                                         |
| `request`           | GlideRecord    | The record of the `HTTP Request [x_snd_eb_http_request]` being used.                                                                                               |
| `options`           | Object         | An object containing specific properties for processing.                                                                                                           |
| `options.is_stream` | Boolean        | True if the inbound payload is a stream.                                                                                                                           |
| `log`               | Object         | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                             |
| `error`             | String         | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.                         |

### Path <a href="#path" id="path"></a>

The Path is used to modify the endpoint for the message. It can be used with inline script evaluation to construct more advanced endpoints. Inline scripts should be wrapped with dollar curly braces `${...}`.

```javascript
/table/incident/${bond.getValue("external_reference")}
```

| Variable      | Type        | Description                                                                                                                                           |
| ------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payload`     | Any         | The payload string or object. Pre-processing can be configured on the Integration to automatically convert JSON to `Object` or XML to `XMLDocument2`. |
| `headers`     | Object      | An object containing the request headers.                                                                                                             |
| `request`     | GlideRecord | The `HTTP Request [x_snd_eb_http_request]` record.                                                                                                    |
| `stage`       | GlideRecord | The `Stage [x_snd_eb_stage]` record.                                                                                                                  |
| `$stage`      | Object      | The dynamic stage which is automatically stored on the stage record.                                                                                  |
| `transaction` | GlideRecord | The current `Transaction [x_snd_eb_transaction]` record.                                                                                              |
| `bond`        | Object      | Instance of Unifi Bond class.                                                                                                                         |
| `message`     | GlideRecord | The record of the `Message` being used.                                                                                                               |
| `scratchpad`  | Object      | An object that can be used to pass variables between scripts.                                                                                         |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.            |

### Outbound condition <a href="#outbound-condition" id="outbound-condition"></a>

The outbound condition is an inline script field useful for simple one-line conditions to be used in conjunction with the filter.

{% hint style="info" %}
More advanced conditions can be made in the [Advanced condition](#advanced-condition) script field.
{% endhint %}

```javascript
current.assignment_group && String(current.assignment_group.u_unifi_integrations).indexOf(message.integration) != -1
```

| Variable    | Type        | Description                                                                                                                                |
| ----------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `current`   | GlideRecord | The record that triggers the message.  The actual table will differ between Processes.                                                     |
| `message`   | GlideRecord | The record of the `Message` being used.                                                                                                    |
| `variables` | Object      | Object used to contain Connection Variables.                                                                                               |
| `log`       | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                     |
| `error`     | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it. |

### Reference lookup script <a href="#reference-lookup-script" id="reference-lookup-script"></a>

The Reference lookup script is used to extract the internal and external message ID's when an inbound request is received. These ID's are used to locate the bond (and therefore the target) the request applies to.

```javascript
// An example reference lookup script
var answer = {};

answer.getExternalMessageID = function (payload, request) {
  return '' + (payload.message.source_id || '');
};

answer.getInternalMessageID = function (payload, request) {
  return '' + (payload.message.target_id || '');
};
```

| Variable    | Type        | Description                                                                                                                                           |
| ----------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payload`   | Any         | The payload string or object. Pre-processing can be configured on the Integration to automatically convert JSON to `Object` or XML to `XMLDocument2`. |
| `request`   | GlideRecord | The record of the `HTTP Request [x_snd_eb_http_request]` being used.                                                                                  |
| `answer`    | Any         | The result of the script being called.                                                                                                                |
| `current`   | GlideRecord | The record that triggers the message.  The actual table will differ between Processes.                                                                |
| `message`   | GlideRecord | The record of the `Message` being used.                                                                                                               |
| `variables` | Object      | Object used to contain Connection Variables.                                                                                                          |
| `log`       | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                |
| `error`     | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.            |

### XML Template <a href="#xml-template" id="xml-template"></a>

The XML Template is evaluated in a similar way to a UI Macro and is extremely useful in constructing advanced XML based payloads using Jelly. Other types of payload can be constructed here, however it's normally easier to do this with the Fields and Field Maps or directly in the Message Scripts.

The XML Template will only be evaluated if the payload has not already been set within the Stage to Request message script.

{% hint style="info" %}
Install the [Unifi Global Utility](https://docs.sharelogic.com/unifi/3.0/release/setup#install-global-utility) for full support of Jelly within XML Templates.
{% endhint %}

```markup
<!-- An example XML template -->
<?xml version="1.0" encoding="utf-8" ?>
<j:jelly trim="false" xmlns:j="jelly:core" xmlns:g="glide" xmlns:j2="null" xmlns:g2="null">
	<g:evaluate jelly="true">
		var transaction = jelly.jvar_transaction;
		var stage = jelly.jvar_stage;
		var message = jelly.jvar_message;
	</g:evaluate>
	<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
		<soapenv:Header />
		<soapenv:Body>
			<MessageName>${HTML:message.message_name}</MessageName>
		</soapenv:Body>
	</soapenv:Envelope>
</j:jelly>	
```

| Variable      | Type        | Description                                                                                                                                           |
| ------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payload`     | Any         | The payload string or object. Pre-processing can be configured on the Integration to automatically convert JSON to `Object` or XML to `XMLDocument2`. |
| `headers`     | Object      | An object containing the request headers.                                                                                                             |
| `request`     | GlideRecord | The `HTTP Request [x_snd_eb_http_request]` record.                                                                                                    |
| `stage`       | GlideRecord | The `Stage [x_snd_eb_stage]` record.                                                                                                                  |
| `$stage`      | Object      | The dynamic stage which is automatically stored on the stage record.                                                                                  |
| `transaction` | GlideRecord | The current `Transaction [x_snd_eb_transaction]` record.                                                                                              |
| `bond`        | Object      | Instance of Unifi Bond class.                                                                                                                         |
| `message`     | GlideRecord | The record of the `Message` being used.                                                                                                               |
| `scratchpad`  | Object      | An object that can be used to pass variables between scripts.                                                                                         |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.            |

## Message Script <a href="#message-script" id="message-script"></a>

### Source to Stage (Outbound) <a href="#source-to-stage-outbound" id="source-to-stage-outbound"></a>

The Source to Stage script is used to capture data from the source record, e.g., an Incident, and save it to the stage record where it is ready to be used to generate a payload.

{% hint style="info" %}
Source data values should be captured in full (including referenced values) in the Source to Stage script.
{% endhint %}

```javascript
// Example source to stage script (using dynamic stage)
$stage.short_description = '' + source.short_description;
```

| Variable      | Type        | Description                                                                                                                                |
| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `source`      | GlideRecord | The record that is being integrated.                                                                                                       |
| `stage`       | GlideRecord | The record of the `Stage [x_snd_eb_stage]` being used. The actual table will differ between Processes.                                     |
| `$stage`      | Object      | The dynamic stage object.                                                                                                                  |
| `transaction` | GlideRecord | The record of the `Transaction [x_snd_eb_transaction]` being used.                                                                         |
| `bond`        | Object      | Instance of Unifi Bond class.                                                                                                              |
| `message`     | GlideRecord | The record of the `Message` being used.                                                                                                    |
| `variables`   | Object      | Object used to contain Connection Variables.                                                                                               |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                     |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it. |

### Stage to Request (Outbound) <a href="#stage-to-request-outbound" id="stage-to-request-outbound"></a>

The Stage to Request script is used to generate a payload using the data captured on the stage.

{% hint style="info" %}
Payload generation and request configuration should be done in the Stage to Request script.
{% endhint %}

```javascript
// Example stage to request script (using dynamic stage)
payload.short_description = $stage.short_description;
```

| Variable      | Type        | Description                                                                                                                                           |
| ------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payload`     | Any         | The payload string or object. Pre-processing can be configured on the Integration to automatically convert JSON to `Object` or XML to `XMLDocument2`. |
| `headers`     | Object      | An object containing the request headers.                                                                                                             |
| `request`     | GlideRecord | The `HTTP Request [x_snd_eb_http_request]` record.                                                                                                    |
| `stage`       | GlideRecord | The `Stage [x_snd_eb_stage]` record.                                                                                                                  |
| `$stage`      | Object      | The dynamic stage which is automatically stored on the stage record.                                                                                  |
| `transaction` | GlideRecord | The current `Transaction [x_snd_eb_transaction]` record.                                                                                              |
| `bond`        | Object      | Instance of Unifi Bond class.                                                                                                                         |
| `message`     | GlideRecord | The record of the `Message` being used.                                                                                                               |
| `scratchpad`  | Object      | An object that can be used to pass variables between scripts.                                                                                         |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.            |

### Payload to Stage (Inbound) <a href="#payload-to-stage-inbound" id="payload-to-stage-inbound"></a>

The Payload to Stage script is used to capture data from the inbound request payload and save it to the stage record where it is ready to be used to update the target record.

```javascript
// Example payload to stage script (using dynamic stage)
$stage.short_description = payload.short_description;
```

{% hint style="info" %}
Data should be extracted from the inbound payload and headers in the Payload to Stage script.
{% endhint %}

| Variable      | Type        | Description                                                                                                                                           |
| ------------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------- |
| `payload`     | Any         | The payload string or object. Pre-processing can be configured on the Integration to automatically convert JSON to `Object` or XML to `XMLDocument2`. |
| `headers`     | Object      | An object containing request headers keyed by header name.                                                                                            |
| `request`     | GlideRecord | The `HTTP Request [x_snd_eb_http_request]` record.                                                                                                    |
| `stage`       | GlideRecord | The `Stage [x_snd_eb_stage]` record.                                                                                                                  |
| `$stage`      | Object      | The dynamic stage which is automatically stored on the stage record.                                                                                  |
| `transaction` | GlideRecord | The current `Transaction [x_snd_eb_transaction]` record.                                                                                              |
| `message`     | GlideRecord | The record of the `Message` being used.                                                                                                               |
| `variables`   | Object      | Object used to contain Connection Variables.                                                                                                          |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                                |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it.            |

### Stage to Target (Inbound) <a href="#stage-to-target-inbound" id="stage-to-target-inbound"></a>

The Stage to Target script is used to update the target record, e.g., an Incident, with the data and references given in the stage.

{% hint style="info" %}
Reference lookups, data validation, and business logic should be done in the Stage to Target script.
{% endhint %}

```javascript
// Example stage to target script (using dynamic stage)
target.short_description = $stage.short_description;
```

| Variable      | Type        | Description                                                                                                                                |
| ------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------ |
| `target`      | GlideRecord | The record that is being integrated.                                                                                                       |
| `stage`       | GlideRecord | The record of the `Stage [x_snd_eb_stage]` being used. The actual table will differ between Processes.                                     |
| `$stage`      | Object      | The dynamic stage object.                                                                                                                  |
| `transaction` | GlideRecord | The record of the `Transaction [x_snd_eb_transaction]` being used.                                                                         |
| `bond`        | Object      | Instance of Unifi Bond class.                                                                                                              |
| `message`     | GlideRecord | The record of the `Message` being used.                                                                                                    |
| `variables`   | Object      | Object used to contain Connection Variables.                                                                                               |
| `log`         | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`.                                     |
| `error`       | String      | The error message to return from the script. Alternatively you can simply throw a `string` or `Error` and the system will take care of it. |

## Field <a href="#field" id="field"></a>

### Default inbound <a href="#default-inbound" id="default-inbound"></a>

The default inbound script can be used so set the default value to be used by the Field Map when no value is found on the stage.

{% hint style="info" %}
See [Stage to Target (Inbound)](#stage-to-target-inbound) for available variables.
{% endhint %}

### Default outbound <a href="#default-outbound" id="default-outbound"></a>

The default outbound script can be used so set the default value to be used by the Field Map when no value is found on the source.

{% hint style="info" %}
See [Source to Stage (Outbound)](#source-to-stage-outbound) for available variables.
{% endhint %}

## Field Map <a href="#field-map" id="field-map"></a>

Fields maps are compiled during Build operations with the field as an input and the resulting code is added to the respective Message Scripts.

Only code contained within dollar-square brackets `$[...]` will be compiled. During inbound/outbound processing, standard Message Script variables will apply.

{% tabs %}
{% tab title="Field Map" %}

```javascript
var is_mandatory = $[field.mandatory];

if (is_mandatory && $payload.$[field.property] == undefined) {
  throw 'Mandatory field $[field.property] was not provided';
} else {
  $stage.$[field.element] = $payload.$[field.property];
}
```

{% endtab %}

{% tab title="Message Script" %}

```javascript
var is_mandatory = false;
  
if (is_mandatory && $payload.short_description == undefined) {
  throw 'Mandatory field short_description was not provided';
} else {
  $stage.short_description = $payload.short_description;
}
```

{% endtab %}
{% endtabs %}

| Variable | Type        | Description                               |
| -------- | ----------- | ----------------------------------------- |
| `field`  | GlideRecord | The record of the `Field` being compiled. |

## Response Action <a href="#response-action" id="response-action"></a>

The Response Action script is executed when Run Script is checked. It can be used to do anything based on a response to an outbound request.

| Variable           | Type        | Description                                                                                            |
| ------------------ | ----------- | ------------------------------------------------------------------------------------------------------ |
| `action`           | GlideRecord | The current `Response Action [x_snd_eb_response_action]` GlideRecord.                                  |
| `bond`             | Object      | Instance of Unifi Bond class.                                                                          |
| `integration`      | GlideRecord | The record of the `Integration [x_snd_eb_integration]` being used.                                     |
| `message`          | GlideRecord | The record of the `Message` being used.                                                                |
| `request`          | GlideRecord | The record of the `HTTP Request [x_snd_eb_http_request]` being used.                                   |
| `response_payload` | Any         | A pre-processed payload string or object.                                                              |
| `transaction`      | GlideRecord | The record of the `Transaction [x_snd_eb_transaction]` being used.                                     |
| `log`              | Object      | Object containing several functions that can be used for logging. `info`, `warn`, `error` and `debug`. |

## Event Action <a href="#event-action" id="event-action"></a>

| Variable  | Type        | Description                                                                      |
| --------- | ----------- | -------------------------------------------------------------------------------- |
| `current` | GlideRecord | The record of the `Transaction [x_snd_eb_transaction]` that triggered the event. |
| `action`  | GlideRecord | The current `Event Action [x_snd_eb_event_action]` GlideRecord.                  |
