> ## 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.

# Automation Reference

> Complete reference for automation triggers, actions, conditions, and templates

# Automation Reference

Complete reference guide for building automations in Alguna. This page documents all available triggers, actions, step types, template syntax, and condition expressions.

***

## Trigger Types

Triggers define when an automation runs. Each trigger provides specific data that can be used in subsequent steps.

### Payment Failed

Fires when a payment attempt fails.

| Property            | Type            | Description                        |
| ------------------- | --------------- | ---------------------------------- |
| `trigger_type`      | `PaymentFailed` | Trigger identifier                 |
| `invoice_id`        | string          | The invoice that failed to collect |
| `payment_method_id` | string          | Payment method used                |
| `failure_code`      | string          | Reason for failure                 |
| `failure_message`   | string          | Human-readable failure message     |
| `attempt_number`    | integer         | Which retry attempt (1, 2, 3...)   |

**Example trigger data:**

```json theme={null}
{
  "trigger_type": "PaymentFailed",
  "invoice_id": "inv_abc123",
  "account_id": "acc_xyz789",
  "payment_method_id": "pm_card_visa",
  "failure_code": "card_declined",
  "failure_message": "Your card was declined",
  "attempt_number": 1,
  "amount": "99.00",
  "currency": "USD"
}
```

***

### Invoice Status Updated

Fires when an invoice status changes.

| Property            | Type                   | Description              |
| ------------------- | ---------------------- | ------------------------ |
| `trigger_type`      | `InvoiceStatusUpdated` | Trigger identifier       |
| `invoice_id`        | string                 | The invoice              |
| `previous_status`   | string                 | Status before change     |
| `new_status`        | string                 | Current status           |
| `status_changed_at` | timestamp              | When the change occurred |

**Status values:** `draft`, `issued`, `paid`, `void`, `past_due`, `uncollectible`

**Example trigger data:**

```json theme={null}
{
  "trigger_type": "InvoiceStatusUpdated",
  "invoice_id": "inv_abc123",
  "account_id": "acc_xyz789",
  "previous_status": "issued",
  "new_status": "paid",
  "status_changed_at": "2024-01-20T10:30:00Z"
}
```

***

### Prepaid Usage Update

Fires when prepaid credit usage changes significantly.

| Property            | Type                 | Description                |
| ------------------- | -------------------- | -------------------------- |
| `trigger_type`      | `PrepaidUsageUpdate` | Trigger identifier         |
| `wallet_id`         | string               | The wallet affected        |
| `previous_balance`  | decimal              | Balance before update      |
| `current_balance`   | decimal              | Current balance            |
| `usage_amount`      | decimal              | Amount consumed            |
| `threshold_crossed` | boolean              | If a threshold was crossed |

**Example trigger data:**

```json theme={null}
{
  "trigger_type": "PrepaidUsageUpdate",
  "wallet_id": "wal_abc123",
  "account_id": "acc_xyz789",
  "previous_balance": "1000.00",
  "current_balance": "150.00",
  "usage_amount": "850.00",
  "threshold_crossed": true,
  "threshold_percentage": 85
}
```

***

### Subscription Sent for Signature

Fires when a subscription requires signature.

| Property          | Type                           | Description                 |
| ----------------- | ------------------------------ | --------------------------- |
| `trigger_type`    | `SubscriptionSentForSignature` | Trigger identifier          |
| `subscription_id` | string                         | The subscription            |
| `version_id`      | string                         | Version requiring signature |
| `sent_to`         | string                         | Email address               |
| `sent_at`         | timestamp                      | When sent                   |

**Example trigger data:**

```json theme={null}
{
  "trigger_type": "SubscriptionSentForSignature",
  "subscription_id": "sub_abc123",
  "version_id": "ver_xyz789",
  "account_id": "acc_def456",
  "sent_to": "contracts@acme.com",
  "sent_at": "2024-01-20T10:30:00Z",
  "expires_at": "2024-01-27T10:30:00Z"
}
```

***

### Credits Depleted

Fires when credit balance reaches zero or a threshold.

| Property        | Type              | Description              |
| --------------- | ----------------- | ------------------------ |
| `trigger_type`  | `CreditsDepleted` | Trigger identifier       |
| `wallet_id`     | string            | The wallet               |
| `depleted_at`   | timestamp         | When depleted            |
| `last_grant_id` | string            | Most recent credit grant |

**Example trigger data:**

```json theme={null}
{
  "trigger_type": "CreditsDepleted",
  "wallet_id": "wal_abc123",
  "account_id": "acc_xyz789",
  "depleted_at": "2024-01-20T10:30:00Z",
  "final_balance": "0.00",
  "last_grant_id": "grant_def456"
}
```

***

### Subscription Status Updated

Fires when a subscription status changes.

| Property          | Type                        | Description          |
| ----------------- | --------------------------- | -------------------- |
| `trigger_type`    | `SubscriptionStatusUpdated` | Trigger identifier   |
| `subscription_id` | string                      | The subscription     |
| `previous_status` | string                      | Status before change |
| `new_status`      | string                      | Current status       |

**Status values:** `draft`, `pending`, `active`, `paused`, `canceled`, `expired`

**Example trigger data:**

```json theme={null}
{
  "trigger_type": "SubscriptionStatusUpdated",
  "subscription_id": "sub_abc123",
  "account_id": "acc_xyz789",
  "previous_status": "active",
  "new_status": "canceled",
  "status_changed_at": "2024-01-20T10:30:00Z",
  "cancellation_reason": "customer_requested"
}
```

***

## Action Types

Actions are the operations performed by your automation.

### Communication Actions

#### send\_email

Send an email using a template.

| Parameter     | Type      | Required | Description                          |
| ------------- | --------- | -------- | ------------------------------------ |
| `template_id` | string    | Yes      | Email template to use                |
| `to`          | string    | Yes      | Recipient email (supports templates) |
| `cc`          | string\[] | No       | CC recipients                        |
| `bcc`         | string\[] | No       | BCC recipients                       |
| `variables`   | object    | No       | Template variables                   |

```json theme={null}
{
  "action": "send_email",
  "parameters": {
    "template_id": "tmpl_payment_failed",
    "to": "{{trigger.account.email}}",
    "variables": {
      "invoice_number": "{{trigger.invoice_id}}",
      "amount_due": "{{trigger.amount}}"
    }
  }
}
```

#### send\_slack\_message

Send a Slack message to a selected channel in a connected Slack workspace.

| Parameter       | Type   | Required | Description                                                                                                                                                             |
| --------------- | ------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `integrationId` | string | Yes      | Slack workspace connection to use. Selected from connected Slack integrations; templates are not allowed.                                                               |
| `channelId`     | string | Yes      | Slack channel to send to. Options load after workspace selection and include public and private channels visible to the connected Slack app; templates are not allowed. |
| `messageBody`   | string | Yes      | Slack message body. Supports markdown and automation templates.                                                                                                         |

If no Slack workspace is connected, users who can manage integrations can connect Slack inline from the automation form. Other users see helper text directing them to **Settings > Integrations**.

```json theme={null}
{
  "action": "send_slack_message",
  "parameters": {
    "integrationId": "int_slack_workspace_123",
    "channelId": "C0123456789",
    "messageBody": "Invoice *{{trigger.invoice_id}}* is overdue for *{{trigger.account.name}}*."
  }
}
```

#### send\_invoice\_reminder

Send a payment reminder for an invoice.

| Parameter       | Type   | Required | Description               |
| --------------- | ------ | -------- | ------------------------- |
| `invoice_id`    | string | Yes      | Invoice to remind about   |
| `reminder_type` | string | No       | `gentle`, `firm`, `final` |

```json theme={null}
{
  "action": "send_invoice_reminder",
  "parameters": {
    "invoice_id": "{{trigger.invoice_id}}",
    "reminder_type": "gentle"
  }
}
```

#### send\_invoice\_reminders\_bulk

Send reminders for multiple invoices.

| Parameter       | Type      | Required | Description              |
| --------------- | --------- | -------- | ------------------------ |
| `invoice_ids`   | string\[] | Yes      | Invoices to remind about |
| `reminder_type` | string    | No       | Reminder severity level  |

```json theme={null}
{
  "action": "send_invoice_reminders_bulk",
  "parameters": {
    "invoice_ids": "{{step_get_invoices.outputs.invoice_ids}}",
    "reminder_type": "firm"
  }
}
```

#### send\_billing\_info\_request

Request updated billing information from customer.

| Parameter    | Type   | Required | Description        |
| ------------ | ------ | -------- | ------------------ |
| `account_id` | string | Yes      | Customer account   |
| `reason`     | string | No       | Why info is needed |

```json theme={null}
{
  "action": "send_billing_info_request",
  "parameters": {
    "account_id": "{{trigger.account_id}}",
    "reason": "Payment method expired"
  }
}
```

#### share\_customer\_portal\_link

Send customer portal access link.

| Parameter    | Type   | Required | Description                  |
| ------------ | ------ | -------- | ---------------------------- |
| `account_id` | string | Yes      | Customer account             |
| `expires_in` | string | No       | Link expiration (e.g., `7d`) |

```json theme={null}
{
  "action": "share_customer_portal_link",
  "parameters": {
    "account_id": "{{trigger.account_id}}",
    "expires_in": "7d"
  }
}
```

#### send\_subscription\_signature\_reminder

Remind customer to sign a pending subscription.

| Parameter         | Type   | Required | Description                     |
| ----------------- | ------ | -------- | ------------------------------- |
| `subscription_id` | string | Yes      | Subscription awaiting signature |
| `version_id`      | string | No       | Specific version                |

```json theme={null}
{
  "action": "send_subscription_signature_reminder",
  "parameters": {
    "subscription_id": "{{trigger.subscription_id}}",
    "version_id": "{{trigger.version_id}}"
  }
}
```

#### send\_subscriptions\_autorenewal\_notification\_bulk

Notify customers about upcoming auto-renewals.

| Parameter          | Type      | Required | Description            |
| ------------------ | --------- | -------- | ---------------------- |
| `subscription_ids` | string\[] | Yes      | Subscriptions renewing |
| `days_before`      | integer   | No       | Days before renewal    |

```json theme={null}
{
  "action": "send_subscriptions_autorenewal_notification_bulk",
  "parameters": {
    "subscription_ids": "{{step_get_subs.outputs.ids}}",
    "days_before": 30
  }
}
```

***

### Data Retrieval Actions

#### get\_invoice

Retrieve a single invoice.

| Parameter    | Type   | Required | Description         |
| ------------ | ------ | -------- | ------------------- |
| `invoice_id` | string | Yes      | Invoice to retrieve |

**Outputs:** Full invoice object including line items, status, amounts.

```json theme={null}
{
  "action": "get_invoice",
  "parameters": {
    "invoice_id": "{{trigger.invoice_id}}"
  }
}
```

#### get\_invoices

Retrieve multiple invoices with filters.

| Parameter    | Type      | Required | Description        |
| ------------ | --------- | -------- | ------------------ |
| `account_id` | string    | No       | Filter by account  |
| `status`     | string\[] | No       | Filter by status   |
| `due_before` | string    | No       | Filter by due date |
| `limit`      | integer   | No       | Max results        |

**Outputs:** Array of invoice objects.

```json theme={null}
{
  "action": "get_invoices",
  "parameters": {
    "account_id": "{{trigger.account_id}}",
    "status": ["issued", "past_due"],
    "limit": 10
  }
}
```

#### get\_subscription

Retrieve a single subscription.

| Parameter         | Type   | Required | Description              |
| ----------------- | ------ | -------- | ------------------------ |
| `subscription_id` | string | Yes      | Subscription to retrieve |

**Outputs:** Full subscription object with current version.

```json theme={null}
{
  "action": "get_subscription",
  "parameters": {
    "subscription_id": "{{trigger.subscription_id}}"
  }
}
```

#### get\_subscriptions

Retrieve multiple subscriptions with filters.

| Parameter       | Type      | Required | Description            |
| --------------- | --------- | -------- | ---------------------- |
| `account_id`    | string    | No       | Filter by account      |
| `status`        | string\[] | No       | Filter by status       |
| `renews_before` | string    | No       | Filter by renewal date |

**Outputs:** Array of subscription objects.

```json theme={null}
{
  "action": "get_subscriptions",
  "parameters": {
    "status": ["active"],
    "renews_before": "{{now | date_add: '30d'}}"
  }
}
```

***

### Billing Actions

#### retry\_invoice\_payment

Retry payment collection for an invoice.

| Parameter           | Type   | Required | Description             |
| ------------------- | ------ | -------- | ----------------------- |
| `invoice_id`        | string | Yes      | Invoice to retry        |
| `payment_method_id` | string | No       | Specific payment method |

```json theme={null}
{
  "action": "retry_invoice_payment",
  "parameters": {
    "invoice_id": "{{trigger.invoice_id}}"
  }
}
```

#### cancel\_subscription

Cancel a subscription.

| Parameter         | Type   | Required | Description                    |
| ----------------- | ------ | -------- | ------------------------------ |
| `subscription_id` | string | Yes      | Subscription to cancel         |
| `cancel_at`       | string | No       | `immediate` or `end_of_period` |
| `reason`          | string | No       | Cancellation reason            |

```json theme={null}
{
  "action": "cancel_subscription",
  "parameters": {
    "subscription_id": "{{trigger.subscription_id}}",
    "cancel_at": "end_of_period",
    "reason": "Non-payment after multiple attempts"
  }
}
```

***

### Integration Actions

#### send\_webhook

Send data to an external webhook.

| Parameter | Type   | Required | Description                 |
| --------- | ------ | -------- | --------------------------- |
| `url`     | string | Yes      | Webhook endpoint            |
| `method`  | string | No       | HTTP method (default: POST) |
| `headers` | object | No       | Custom headers              |
| `body`    | object | Yes      | Request payload             |

```json theme={null}
{
  "action": "send_webhook",
  "parameters": {
    "url": "https://api.yourapp.com/billing-events",
    "method": "POST",
    "headers": {
      "Authorization": "Bearer {{secrets.WEBHOOK_TOKEN}}"
    },
    "body": {
      "event": "payment_failed",
      "account_id": "{{trigger.account_id}}",
      "invoice_id": "{{trigger.invoice_id}}"
    }
  }
}
```

***

## Step Types

Automations are composed of steps that execute in sequence.

### Action Step

Execute a single action.

```json theme={null}
{
  "id": "send_reminder",
  "type": "Action",
  "action": "send_email",
  "parameters": {...}
}
```

### Condition Step

Branch based on a condition.

```json theme={null}
{
  "id": "check_attempts",
  "type": "Condition",
  "condition": "trigger.attempt_number > 2",
  "then": [...],
  "else": [...]
}
```

### Delay Step

Wait before continuing.

```json theme={null}
{
  "id": "wait_24h",
  "type": "Delay",
  "duration": "24h"
}
```

**Duration formats:** `30m` (minutes), `24h` (hours), `7d` (days)

### ForEach Step

Iterate over a collection.

```json theme={null}
{
  "id": "process_invoices",
  "type": "ForEach",
  "collection": "{{step_get_invoices.outputs.invoices}}",
  "item_variable": "invoice",
  "steps": [
    {
      "id": "send_reminder",
      "type": "Action",
      "action": "send_invoice_reminder",
      "parameters": {
        "invoice_id": "{{invoice.id}}"
      }
    }
  ]
}
```

### DoUntil Step

Repeat until a condition is met.

```json theme={null}
{
  "id": "retry_payment",
  "type": "DoUntil",
  "condition": "step_check_status.outputs.status == 'paid' || iteration > 3",
  "steps": [
    {
      "id": "attempt_payment",
      "type": "Action",
      "action": "retry_invoice_payment",
      "parameters": {...}
    },
    {
      "id": "wait",
      "type": "Delay",
      "duration": "24h"
    }
  ]
}
```

***

## Template Syntax

Use templates to reference dynamic data in your automation.

### Basic Syntax

Access data using double curly braces:

```
{{trigger.account_id}}
{{step_id.outputs.field}}
{{variable_name}}
```

### Accessing Trigger Data

```
{{trigger.invoice_id}}        // Direct field
{{trigger.account.name}}      // Nested field
{{trigger.account.email}}     // Customer email
```

### Accessing Step Outputs

Reference outputs from previous steps:

```
{{step_get_invoice.outputs.total}}
{{step_get_subscription.outputs.plan_id}}
{{step_get_invoices.outputs.invoices[0].id}}
```

### Built-in Variables

| Variable          | Description                                 |
| ----------------- | ------------------------------------------- |
| `{{now}}`         | Current timestamp                           |
| `{{today}}`       | Current date                                |
| `{{iteration}}`   | Current loop iteration (in ForEach/DoUntil) |
| `{{secrets.KEY}}` | Access stored secrets                       |

### Filters

Transform values with filters:

```
{{trigger.amount | currency}}           // Format as currency
{{trigger.due_date | date: 'MMM D'}}   // Format date
{{trigger.name | uppercase}}            // Convert to uppercase
{{trigger.name | lowercase}}            // Convert to lowercase
{{trigger.items | length}}              // Array length
{{now | date_add: '7d'}}                // Add to date
{{now | date_subtract: '30d'}}          // Subtract from date
```

***

## Condition Syntax

Conditions use the Expr expression language.

### Comparison Operators

| Operator | Description      | Example                       |
| -------- | ---------------- | ----------------------------- |
| `==`     | Equal            | `trigger.status == 'paid'`    |
| `!=`     | Not equal        | `trigger.status != 'draft'`   |
| `>`      | Greater than     | `trigger.amount > 100`        |
| `>=`     | Greater or equal | `trigger.attempt_number >= 3` |
| `<`      | Less than        | `trigger.balance < 50`        |
| `<=`     | Less or equal    | `trigger.days_overdue <= 30`  |

### Logical Operators

| Operator | Description | Example                                                  |
| -------- | ----------- | -------------------------------------------------------- |
| `&&`     | AND         | `trigger.status == 'past_due' && trigger.amount > 100`   |
| `\|\|`   | OR          | `trigger.status == 'paid' \|\| trigger.status == 'void'` |
| `!`      | NOT         | `!trigger.is_test`                                       |

### String Operations

```
trigger.email contains '@gmail.com'
trigger.name startsWith 'Acme'
trigger.description endsWith 'trial'
trigger.plan_id in ['plan_basic', 'plan_pro']
```

### Array Operations

```
len(trigger.line_items) > 0
trigger.tags contains 'enterprise'
any(trigger.invoices, {.status == 'past_due'})
all(trigger.payments, {.status == 'succeeded'})
```

### Null Checks

```
trigger.discount != nil
trigger.coupon_code ?? 'NONE'
```

***

## Complete Examples

### Dunning Automation

Progressive payment failure handling:

```json theme={null}
{
  "name": "Payment Dunning Workflow",
  "trigger": {
    "type": "PaymentFailed"
  },
  "steps": [
    {
      "id": "check_attempt",
      "type": "Condition",
      "condition": "trigger.attempt_number == 1",
      "then": [
        {
          "id": "gentle_reminder",
          "type": "Action",
          "action": "send_email",
          "parameters": {
            "template_id": "tmpl_payment_failed_gentle",
            "to": "{{trigger.account.email}}"
          }
        },
        {
          "id": "wait_3_days",
          "type": "Delay",
          "duration": "3d"
        },
        {
          "id": "retry_1",
          "type": "Action",
          "action": "retry_invoice_payment",
          "parameters": {
            "invoice_id": "{{trigger.invoice_id}}"
          }
        }
      ],
      "else": [
        {
          "id": "check_final",
          "type": "Condition",
          "condition": "trigger.attempt_number >= 3",
          "then": [
            {
              "id": "final_notice",
              "type": "Action",
              "action": "send_email",
              "parameters": {
                "template_id": "tmpl_payment_failed_final",
                "to": "{{trigger.account.email}}"
              }
            },
            {
              "id": "cancel_sub",
              "type": "Action",
              "action": "cancel_subscription",
              "parameters": {
                "subscription_id": "{{trigger.subscription_id}}",
                "cancel_at": "immediate",
                "reason": "Payment failed after 3 attempts"
              }
            }
          ]
        }
      ]
    }
  ]
}
```

### Renewal Notification Automation

Notify customers before renewal:

```json theme={null}
{
  "name": "Renewal Notifications",
  "trigger": {
    "type": "SubscriptionStatusUpdated",
    "filters": {
      "new_status": "active"
    }
  },
  "schedule": {
    "cron": "0 9 * * *"
  },
  "steps": [
    {
      "id": "get_renewing_subs",
      "type": "Action",
      "action": "get_subscriptions",
      "parameters": {
        "status": ["active"],
        "renews_before": "{{now | date_add: '30d'}}"
      }
    },
    {
      "id": "filter_annual",
      "type": "Condition",
      "condition": "len(step_get_renewing_subs.outputs.subscriptions) > 0",
      "then": [
        {
          "id": "notify_customers",
          "type": "Action",
          "action": "send_subscriptions_autorenewal_notification_bulk",
          "parameters": {
            "subscription_ids": "{{step_get_renewing_subs.outputs.subscriptions | map: 'id'}}"
          }
        }
      ]
    }
  ]
}
```

### Low Credit Balance Alert

Alert when credits are running low:

```json theme={null}
{
  "name": "Low Credit Alert",
  "trigger": {
    "type": "PrepaidUsageUpdate"
  },
  "steps": [
    {
      "id": "check_threshold",
      "type": "Condition",
      "condition": "trigger.threshold_crossed && trigger.threshold_percentage >= 80",
      "then": [
        {
          "id": "alert_customer",
          "type": "Action",
          "action": "send_email",
          "parameters": {
            "template_id": "tmpl_low_credits",
            "to": "{{trigger.account.email}}",
            "variables": {
              "remaining_balance": "{{trigger.current_balance}}",
              "usage_percentage": "{{trigger.threshold_percentage}}"
            }
          }
        },
        {
          "id": "notify_webhook",
          "type": "Action",
          "action": "send_webhook",
          "parameters": {
            "url": "{{secrets.SLACK_WEBHOOK}}",
            "body": {
              "text": "Low credit alert: {{trigger.account.name}} at {{trigger.threshold_percentage}}% usage"
            }
          }
        }
      ]
    }
  ]
}
```

***

## Error Handling

### Retry Configuration

Configure retry behavior for actions:

```json theme={null}
{
  "action": "send_webhook",
  "parameters": {...},
  "retry": {
    "max_attempts": 3,
    "backoff": "exponential",
    "initial_delay": "30s"
  }
}
```

### On Error Handling

Define behavior when a step fails:

```json theme={null}
{
  "id": "risky_action",
  "type": "Action",
  "action": "retry_invoice_payment",
  "parameters": {...},
  "on_error": {
    "action": "continue",
    "notify": "{{secrets.ALERT_EMAIL}}"
  }
}
```

**Error actions:**

* `stop` - Halt automation
* `continue` - Skip and continue
* `goto` - Jump to specific step

***

## Best Practices

<CardGroup cols={2}>
  <Card title="Use Descriptive IDs" icon="tag">
    Name steps clearly: `send_gentle_reminder` not `step_1`.
  </Card>

  <Card title="Test with Small Batches" icon="flask">
    Test automations with filtered triggers before going live.
  </Card>

  <Card title="Add Delays Thoughtfully" icon="clock">
    Avoid overwhelming customers with rapid-fire communications.
  </Card>

  <Card title="Log External Calls" icon="scroll">
    Use webhooks to log automation events for debugging.
  </Card>
</CardGroup>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="Automation Overview" icon="wand-magic-sparkles" href="/automations/overview">
    Getting started with automations.
  </Card>

  <Card title="Triggers" icon="bolt" href="/automations/triggers">
    Learn about trigger types.
  </Card>

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

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