> ## Documentation Index
> Fetch the complete documentation index at: https://alguna.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Automations Overview

> Build powerful workflows to automate your billing operations

# Automations

Automations allow you to build powerful, event-driven workflows that respond to billing events, customer actions, and scheduled triggers. From sending dunning emails to syncing data with external systems, automations help you scale your operations without manual intervention.

***

## What Are Automations?

Automations are configurable workflows that:

* **Trigger** based on events or schedules
* **Evaluate conditions** to determine if actions should run
* **Execute actions** like sending emails, updating records, or calling APIs
* **Branch and loop** for complex logic

```mermaid theme={null}
graph LR
    A[Trigger] --> B{Condition}
    B -->|True| C[Action 1]
    C --> D[Action 2]
    B -->|False| E[Skip]
    D --> F[End]
    E --> F
```

***

## Key Concepts

### Triggers

Triggers define **when** an automation runs:

| Type     | Description                       |
| -------- | --------------------------------- |
| Event    | Runs when a specific event occurs |
| Schedule | Runs on a time-based schedule     |
| Manual   | Runs when triggered via API       |

### Conditions

Conditions filter **whether** the automation should continue:

```plaintext theme={null}
IF invoice.amount > 1000
AND customer.segment = "enterprise"
THEN continue
ELSE skip
```

### Actions

Actions are the **operations** performed:

* Send email
* Send SMS
* Create task
* Update record
* Call webhook
* Retry payment

### Steps

Steps are the building blocks combined into a workflow:

* **Action steps** - Execute a single action
* **Condition steps** - Branch based on logic
* **Delay steps** - Wait before continuing
* **Loop steps** - Iterate over collections

***

## Supported Triggers

### Event Triggers

| Event                      | Description                       |
| -------------------------- | --------------------------------- |
| `invoice.issued`           | Invoice was issued                |
| `invoice.paid`             | Invoice was paid                  |
| `invoice.overdue`          | Invoice became overdue            |
| `payment.failed`           | Payment attempt failed            |
| `payment.succeeded`        | Payment succeeded                 |
| `subscription.activated`   | Subscription became active        |
| `subscription.canceled`    | Subscription was canceled         |
| `subscription.ending_soon` | Subscription ending within X days |
| `customer.created`         | New customer created              |
| `credits.depleted`         | Credit balance reached zero       |
| `usage.threshold_exceeded` | Usage exceeded threshold          |

### Schedule Triggers

| Type     | Example                       |
| -------- | ----------------------------- |
| Interval | Every 24 hours                |
| Cron     | `0 9 * * 1` (Mondays at 9 AM) |
| Calendar | First day of month            |

***

## Available Actions

### Communication

| Action               | Description                                                   |
| -------------------- | ------------------------------------------------------------- |
| `send_email`         | Send templated email                                          |
| `send_sms`           | Send SMS message                                              |
| `send_slack_message` | Send a markdown Slack message to a selected workspace channel |
| `send_webhook`       | Call external webhook                                         |

### Billing

| Action               | Description              |
| -------------------- | ------------------------ |
| `retry_payment`      | Retry failed payment     |
| `void_invoice`       | Void an invoice          |
| `create_credit_note` | Generate credit note     |
| `apply_credits`      | Apply credits to invoice |

### Records

| Action            | Description            |
| ----------------- | ---------------------- |
| `update_customer` | Update customer fields |
| `add_tag`         | Add tag to customer    |
| `create_task`     | Create internal task   |
| `sync_to_crm`     | Sync data to CRM       |

### Workflow

| Action   | Description           |
| -------- | --------------------- |
| `delay`  | Wait for duration     |
| `branch` | Conditional branching |
| `loop`   | Iterate over items    |
| `stop`   | End workflow          |

***

## Creating Automations via Dashboard

### Step 1: Create the Automation

1. Navigate to **Settings → Automations**
2. Click **Create Automation**
3. Choose how to start:
   * **From Template**: Select a pre-built template (Dunning, Welcome Series, etc.)
   * **From Scratch**: Build a custom automation

### Step 2: Configure the Trigger

1. Select **Trigger Type**:
   * **Event**: Runs when something happens (e.g., payment failed)
   * **Schedule**: Runs on a schedule (daily, weekly, etc.)
2. Choose the specific event or schedule
3. Click **Next**

### Step 3: Add Conditions (Optional)

Filter when the automation should run:

1. Click **Add Condition**
2. Build your condition:
   * Field: `invoice.amount`, `customer.segment`, etc.
   * Operator: equals, greater than, contains
   * Value: The value to compare
3. Combine multiple conditions with AND/OR
4. Click **Next**

### Step 4: Add Actions

1. Click **Add Action**
2. Choose action type:
   * **Send Email**: Select template and recipients
   * **Send SMS**: Configure message
   * **Retry Payment**: Attempt payment again
   * **Update Record**: Change customer/subscription fields
   * **Wait**: Delay before next action
3. Configure action settings
4. Add more actions as needed

For `send_slack_message`, select a connected Slack workspace first, then choose a channel from that workspace. Channel options include public and private channels that the connected Slack app can access. If Slack is not connected yet, users with integration management access can connect Slack inline from the action form.

### Step 5: Test and Activate

1. Click **Test Automation** to run with sample data
2. Review the test results
3. Click **Activate** when ready

### Example: Payment Dunning Workflow

1. Create automation with trigger: **Payment Failed**
2. Add action: Send email (template: "Payment Failed - Gentle Reminder")
3. Add wait: 3 days
4. Add condition: If invoice still unpaid
5. Add action: Retry payment
6. Add action: Send email (template: "Payment Failed - Urgent")
7. Add wait: 7 days
8. Add action: Final notice email
9. Activate

***

## Managing Automations

### View Executions

1. Navigate to **Automations → \[Automation Name]**
2. Click **Executions** tab
3. See each run with status, trigger details, and results
4. Click any execution to see step-by-step log

### Pause/Resume

1. Find the automation in the list
2. Click the toggle to pause or resume
3. Paused automations won't trigger until resumed

### Version History

1. Open the automation
2. Click **Versions**
3. View previous versions
4. Restore if needed

***

## Automation Templates

Start with pre-built templates in the dashboard:

| Template              | Description                             |
| --------------------- | --------------------------------------- |
| **Payment Dunning**   | Multi-step sequence for failed payments |
| **Welcome Series**    | Onboarding emails for new customers     |
| **Renewal Reminder**  | Notify before subscription renewal      |
| **Usage Alert**       | Alert when usage exceeds threshold      |
| **Win-back Campaign** | Re-engage canceled customers            |

***

## Quick Start (API)

### Example: Payment Failed Dunning

```yaml theme={null}
name: Payment Failed - Dunning Email
trigger:
  type: event
  event: payment.failed

steps:
  - type: condition
    if: "{{trigger.failureCount}} == 1"
    then:
      - type: action
        action: send_email
        template: payment_failed_first
        to: "{{trigger.customer.email}}"

  - type: delay
    duration: "3d"

  - type: condition
    if: "{{invoice.status}} == 'unpaid'"
    then:
      - type: action
        action: retry_payment
```

***

## Template Variables

Access data from the trigger context using template syntax:

### Invoice Variables

```plaintext theme={null}
{{invoice.id}}
{{invoice.total}}
{{invoice.currency}}
{{invoice.status}}
{{invoice.dueDate}}
{{invoice.customer.name}}
{{invoice.customer.email}}
```

### Payment Variables

```plaintext theme={null}
{{payment.id}}
{{payment.amount}}
{{payment.status}}
{{payment.failureReason}}
{{payment.failureCount}}
```

### Customer Variables

```plaintext theme={null}
{{customer.id}}
{{customer.name}}
{{customer.email}}
{{customer.segment}}
{{customer.createdAt}}
```

***

## Automation Templates

Start with pre-built templates:

<CardGroup cols={2}>
  <Card title="Payment Dunning" icon="credit-card">
    Multi-step dunning sequence for failed payments.
  </Card>

  <Card title="Welcome Series" icon="envelope">
    Onboarding email sequence for new customers.
  </Card>

  <Card title="Renewal Reminder" icon="calendar">
    Notify customers before subscription renewal.
  </Card>

  <Card title="Usage Alert" icon="chart-line">
    Alert when usage exceeds threshold.
  </Card>
</CardGroup>

***

## Versioning

Automations support versioning for safe updates:

| Version State | Description                     |
| ------------- | ------------------------------- |
| `draft`       | Work in progress, not active    |
| `active`      | Currently running version       |
| `inactive`    | Previously active, now disabled |

### Version Workflow

```mermaid theme={null}
graph LR
    A[Create Draft] --> B[Edit & Test]
    B --> C[Activate]
    C --> D[Active Version]
    D --> E[Create New Draft]
    E --> B
    D --> F[Deactivate]
    F --> G[Inactive]
```

***

## Execution Tracking

### View Executions

Monitor automation runs at **Automations > Executions**:

* Execution status (success, failed, running)
* Trigger details
* Step-by-step execution log
* Error messages

### Execution API

```bash theme={null}
curl https://api.alguna.io/automations/auto_123/executions \
  -H "Authorization: Bearer YOUR_API_KEY"
```

**Response:**

```json theme={null}
{
  "executions": [
    {
      "id": "exec_456",
      "status": "completed",
      "triggeredBy": "invoice.paid",
      "triggeredAt": "2024-01-20T10:00:00Z",
      "completedAt": "2024-01-20T10:00:05Z",
      "stepsExecuted": 3
    }
  ]
}
```

***

## Error Handling

### Retry Configuration

Configure automatic retries for failed steps:

```json theme={null}
{
  "errorHandling": {
    "retries": 3,
    "retryDelay": "5m",
    "backoffMultiplier": 2
  }
}
```

### Fallback Actions

Define fallback actions when steps fail:

```yaml theme={null}
steps:
  - type: action
    action: send_email
    onError:
      - type: action
        action: create_task
        assignee: "{{trigger.accountOwner}}"
        message: "Email failed to send"
```

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Start Simple" icon="seedling">
    Begin with single-step automations, then add complexity.
  </Card>

  <Card title="Test Thoroughly" icon="flask">
    Use draft versions and test data before activating.
  </Card>

  <Card title="Monitor Executions" icon="eye">
    Regularly review execution logs for failures.
  </Card>

  <Card title="Use Templates" icon="copy">
    Start from templates and customize as needed.
  </Card>
</CardGroup>

***

## Use Cases

### Dunning Management

Automate payment recovery:

1. Send email on first failure
2. Wait 3 days
3. Send second email with payment link
4. Wait 5 days
5. Retry payment automatically
6. Escalate to collections if still unpaid

### Subscription Renewal

Notify customers before renewal:

1. 30 days before: Send renewal reminder
2. 7 days before: Send confirmation request
3. On renewal: Send receipt

### Usage Alerts

Monitor and alert on usage:

1. Check usage threshold daily
2. If exceeded: Send alert to customer
3. If > 120%: Notify account manager

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Triggers" icon="bolt" href="/automations/triggers">
    Learn about trigger configuration.
  </Card>

  <Card title="Actions" icon="play" href="/automations/actions">
    Explore available actions.
  </Card>

  <Card title="Conditions" icon="code-branch" href="/automations/conditions">
    Master conditional logic.
  </Card>
</CardGroup>
