# Email notifications

Source: https://developers.swell.is/guides/notifications

Notifications are transactional emails to inform customers and admin users about events that have occurred in your store. They are triggered when a record is modified and specific conditions are met, rendered using Liquid templates, and delivered by Swell.

Notifications can be created and customized using [Swell Apps](https://developers.swell.is/apps/notifications), or by editing notification templates directly in the Swell dashboard under **Settings → Notifications**.

Swell has standard notifications for common ecommerce flows like order and shipping confirmations, subscription lifecycle events, abandoned carts, and gift card purchases. You can edit the templates for these, as well as create custom notifications to suit your particular needs.

## Configuration

| Property | Type | Description |
| --- | --- | --- |
| name | slug | Identifier for the notification. |
| label | string | Label displayed in Swell dashboard. |
| model | slug | Data model the notification is associated with. |
| enabled | boolean | Indicates the notification is enabled. |
| admin | boolean | Indicates whether the notification is sent to admin users. |
| contact | string | Field on model containing recipient address, if applicable. |
| from | string | Sender email address. |
| cc | string | Email addresses to add to CC. |
| bcc | string | Email addresses to add to BCC. |
| replyto | string | Reply to email address used instead of default. |
| subject | string | Email subject line. |
| conditions | object | Conditions evaluated to send the notification. |
| repeat | boolean | Indicates the notification is triggered repeatedly for the same record by different events. |
| new | boolean | Indicates the notifications is triggered when creating new records only. |
| delay | integer | Number of minutes to delay sending the notification after the event occurred |
| fields | array | Variables editable by admins in the Swell dashboard. |
| content | object | HTML or text template for email body. |
| query | object | Query to run when rendering template, adding data to the template context. |
| sample | object | Dummy data for the template preview. |

#### Conditions

Conditions can define a set of criteria that must be met for a notification to be sent. The syntax for this object is the same as the [`where` filter query](https://developers.swell.is/backend-api/querying/filtering), and supports comparison, evaluation, and logical operators. Setting conditions: false means the notification will never be triggered automatically.

The following are a few examples from standard notifications.

**Condition examples**

```json
// Password reset
"conditions": {
  "$data": {
    "$notify": "password-reset",
    "password_reset_url": {
      "$exists": true
    }
  }
}

// Subscription invoice
"conditions": {
  "$data": {
    "$notify": "invoice"
  },
  "grand_total": {
    "$gt": 0
  }
}

// Giftcard fulfillment
"conditions": {
  "send_email": {
    "$ne": null
  }
}
```

#### Repeat

When a record associated with a notification is modified, Swell first checks whether the notification has been sent before. Depending on the notification’s purpose, it should be sent only once, or every time the conditions are met. If repeat is true, it will be triggered every time the conditions are met for a given record. If repeat is false or not specified, it will only be triggered once per record.

#### New

When `true`, the notification conditions will only be evaluated when a record is created, and repeat will have no effect.

#### Delay

If you want the system to wait before sending a notification, you can specify a delay time in minutes.

#### Fields

A list of content fields which can be edited by admin users in the dashboard. These values are available in the template context along with the record object which triggered the notification. You can also utilize record fields within content fields, as shown in the example below.

The following are a few examples from standard notifications.

**Field examples**

```json
// Order confirmation
"fields": [
	{
    "id": "prep_note",
    "label": "Preparation note",
    "type": "long_text",
	  "default": "We're getting your order ready and we'll notify you when it's {% if shipping.pickup %}available for pickup{% else %}shipped{% endif %}."
  },
]

// Shipment confirmation
"fields": [
	{
	  "id": "shipped_note",
	  "label": "Shipped note",
	  "type": "short_text",
	  "default": "Your shipment is on the way"
	},
]

// Password reset
"fields": [
	{
    "id": "reset_note",
    "label": "Reset note",
    "type": "long_text",
    "default": "Use the following link to reset your password for {{ store.name }}. If you didn't request this action, you may safely ignore this email."
  },
]
```

#### Content

This represents the template for the email body, either as plain text or HTML. If creating a notification via API, this must be provided as a string. Once created, Swell stores this as a file.

#### Query

When a notification is triggered, the associated record is fetched with a GET request. The query object can contain [query parameters](https://developers.swell.is/backend-api/querying/query-parameters) to modify this request, which is useful if you need to expand other objects referenced in the record.

**Query examples**

```json
// Subscription invoice
...
"query": {
  "expand": [
		// Customer account referenced in the subscription
    "account",
		// Product and variant referenced in the subscription
    "product",
    "variant",
		// Products and variants referenced in the subscription items
    "items.product", 
    "items.variant"
  ]
},
...

// Shipment confirmation
...
"query": {
  "expand": [
		// Customer account referenced in the order
    "account",
		// Shipments referenced in the order, 
		// plus products and variants referenced in the shipment items
    "shipments",
    "shipments.items.product",
    "shipments.items.variant"
  ]
},
...

// Abandoned cart recovery
...
"query": {
  "expand": [
		// Customer account referenced in the cart
    "account",
		// Products, variants, and bundles referenced in the subscription items
    "items.product",
    "items.variant",
    "items.bundle_items.product",
    "items.bundle_items.variant"
  ]
},
...
```

#### Sample

These are dummy data values used in the dashboard when previewing templates. The object structure should match the record as defined by the target model, so that the field paths for the template variables are the same.

## Templates

Notification templates are used to render the message content, either in plain text or HTML. Templates support [Liquid syntax](https://developers.swell.is/storefronts/swell-liquid-reference), with some additional operators unique to Swell.

#### Variables

Objects and variables are rendered when enclosed in double curly braces {{ and }}. Nested values can be accessed using dot notation.

**Record data**

Fields on the record that triggered the notification can be accessed using the field ID, without any prefix. For example, if the notification is associated with the orders model, the shipping city could be rendered with {{ shipping.city }}.

**Content fields**

If the notification configuration has fields defined, values can be accessed using content.<field_id>. For example, if the notification has a field with the ID welcome_note, the value could be rendered in the template with {{ content.welcome_note }}.

**Store settings**

The store object contains settings for the store, such as name, contact email, logo, and locales. These values can be accessed using store.<field_id>.

#### Logic

Liquid has various tags and operators for working with data in templates. For a more detailed overview, see our [Swell Liquid reference](https://developers.swell.is/storefronts/swell-liquid-reference).

**Assigning variables**

Variables can be assigned anywhere in your template (including loops) to make the code more readable.

**Assigning variables**

```liquid
{% assign logo_width = store.logo_width %}
```

**Controlling flow**

The [tags](https://developers.swell.is/storefronts/swell-liquid-reference/liquid-tags) if, unless, elsif, else, case, and when can be used for conditional rendering.

**Controlling flow**

```liquid
{% if store.logo.file.url %}
  {% if store.logo_width > 0 %}
    {% assign logo_width = store.logo_width %}
  {% else %}
    {% assign logo_width = 200 %}
  {% endif %}
  {% assign logo_width_img = logo_width | times: 2 %}
  <img src="{{ store.logo | img_url: 'padded=true&width=' | append: logo_width_img }}" aria-hidden="true" width="{{ logo_width }}">
{% else %}
  <div>{{ store.name }}</div>
{% endif %}
```

**Iterating over arrays**

The `for` tag can iterate over arrays, hashes, and ranges of integers. Many data structures in Swell involve arrays, so it’s likely you’ll need to loop through items to render certain content.

**Iterating over arrays**

```liquid
{% for item in shipment.items %}
  {{ item.description }}
{% endfor %}
```

**Formatting output**

[Filters](https://developers.swell.is/storefronts/swell-liquid-reference/liquid-filters) can alter the rendered output and apply consistent formatting. Some filters take parameters as an argument.

**Formatting output**

```liquid
{{ date_created | date: '%b %d, %Y' }}
```

## Sending

Notifications are normally sent automatically when record conditions are met, however they can also be triggered with [Backend API](https://developers.swell.is/backend-api/introduction) calls to control their timing and content.

**Send a notification via API**

Using the `$notify` property when creating or updating a record to trigger a notification with an API call.

**Example**

**Node**

```javascript
await swell.put('/orders/{id}', {
  id: "145000197b2bbf62b1e30767",
  $notify: "receipt",
});
```

You may also pass additional fields to update the record, and optionally pass extra data to the notification itself that will be made available in the template. `$notify.data` is merged with record data passed to the notification template.

**Example**

**Node**

```javascript
await swell.put('/orders/{id}', {
  id: "145000197b2bbf62b1e30767",
  // ...optional values to update the record
  $notify: {
    id: "receipt",
    data: {
      my_custom_data: 999999,
    }
  }	
});
```

**Prevent a notification via API**

In cases where a notification is configured to be sent when creating or updating a record, you can prevent it using `$notify: false`.

**Example**

**Node**

```javascript
await swell.post('/orders', {
  cart_id: "145000197b2bbf62b1e3076b",
  $notify: false
});
```

**Send notification by creating an event**

Another way to trigger a notification is to create a record in the `notifications` collection with the following properties. In this way, you can specify the recipient `to` address, where normally it would be derived from the notification's `contact` configuration.

**Example**

`POST /notifications`

**Node**

```javascript
await swell.post('/notifications', {
  template: "orders.receipt", // Model and notification name
  record_id: "62b9f39d8b9a9a00133b7784", // ID of record to send notification for
  to: "user@example.com", // Optional recipient override
  from: "orders@example.com", // Optional sender override
  subject: "Order {{ number }}", // Optional subject override
  test: true // Optional flag to use sample data
});
```

## Testing

Notifications can be viewed and tested directly from the Swell dashboard, in **Settings → Notifications**. You can also send notifications using the Backend API using one of the approaches above.

The notification configuration supports `sample` data objects to use when testing, while live data from actual events is utilized when the system automatically triggers notifications. The `sample` data object must match the structure of the model the notification is associated with
