Rules and Actions

Automate business processes with rules and actions

Rules and Actions

Rules and Actions are the foundation of automation in Appivo. Rules define WHEN automation occurs, and Actions define WHAT happens.

Understanding Rules

A Rule is a trigger that watches for specific events and executes actions when conditions are met.

Rule Types

Rule TypeTriggerUse Case
DATARecord create/update/deleteReact to data changes
SCHEDULEDSpecific timesRecurring tasks, reports
RESTExternal API callsIntegration endpoints
TIMEBASEDTime intervalsPolling, periodic checks
MESSAGEMessages receivedMessage processing
MAILIncoming emailsEmail processing
SMSIncoming SMSSMS processing
MANUALUser actionOn-demand operations
CHAINOther rule completesMulti-step workflows

DATA Rules

Respond to data changes in your models.

Configuration

  • Model - Which model to watch
  • Event - CREATE, UPDATE, DELETE, or ALL
  • Condition - Optional filter for when to trigger

Example: Welcome Email

Send a welcome email when a new customer is created:

Rule: Welcome New Customer
Type: DATA
Model: Customer
Event: CREATE
Condition: (none - trigger for all new customers)
Action: SENDMAIL with welcome template

Example: Status Change Notification

Notify when an order status changes to "Shipped":

Rule: Order Shipped Notification
Type: DATA
Model: Order
Event: UPDATE
Condition: status changed to "Shipped"
Actions:
  1. SENDMAIL to customer
  2. SENDPUSH to mobile app

SCHEDULED Rules

Run at specific times using cron-style scheduling.

Configuration

  • Schedule - When to run (daily, weekly, monthly, custom)
  • Time Zone - For consistent timing

Example: Weekly Report

Generate a sales report every Monday:

Rule: Weekly Sales Report
Type: SCHEDULED
Schedule: Every Monday at 9:00 AM
Time Zone: Europe/Stockholm
Actions:
  1. SCRIPT to aggregate data
  2. SENDMAIL with report

Example: Daily Cleanup

Archive old records daily:

Rule: Archive Old Records
Type: SCHEDULED
Schedule: Every day at 2:00 AM
Action: SCRIPT to move records older than 90 days

REST Rules

Create API endpoints that external systems can call.

Configuration

  • Endpoint - URL path for the API
  • Method - HTTP method (GET, POST, PUT, DELETE)
  • Authentication - Required credentials

Example: External Order Processing

Rule: Process External Order
Type: REST
Endpoint: /api/orders/process
Method: POST
Authentication: API Key required
Actions:
  1. SCRIPT to validate order data
  2. SCRIPT to create order record
  3. WEBHOOK to notify fulfillment system

CHAIN Rules

Create multi-step workflows by chaining rules together.

How It Works

  1. First rule executes and completes
  2. CHAIN rule triggers automatically
  3. Next actions execute with previous results

Example: Order Fulfillment Workflow

Step 1: Order Created (DATA rule)
  → Validate inventory

Step 2: Inventory Validated (CHAIN rule)
  → Create shipment record
  → Update order status

Step 3: Shipment Created (CHAIN rule)
  → Send confirmation email
  → Notify warehouse via webhook

Understanding Actions

Actions define what operations execute when rules trigger.

Action Types

Action TypePurposeExample
SCRIPTCustom JavaScript codeComplex calculations
SENDMAILSend emailsNotifications, reports
SENDSMSSend text messagesAlerts, verification
SENDPUSHPush notificationsMobile alerts
WEBHOOKCall external APIsIntegrations
SERVERServer operationsSystem tasks
SSHRemote commandsServer management
FTPFile transfersData exchange
SFTPSecure file transfersSecure data exchange

SCRIPT Actions

Write custom JavaScript for complex business logic.

Script Structure

'use strict';
exports.execute = async function(context, params) {
    try {
        // Your logic here

        return { success: true, data: result };
    } catch (error) {
        return { success: false, error: error.message };
    }
};

Context Object

The context object provides access to:

  • Query data - Fetch records from models
  • Create records - Insert new data
  • Update records - Modify existing data
  • Delete records - Remove data
  • AI Functions - Invoke AI agents for intelligent automation
  • Configuration - Access settings
  • Logging - Add debug information

Example: Calculate Order Total

'use strict';
exports.execute = async function(context, params) {
    try {
        // Get order items
        const items = await context.query('OrderItem', {
            filter: { order_id: params.orderId }
        });

        // Calculate total
        let total = 0;
        for (const item of items) {
            total += item.quantity * item.unit_price;
        }

        // Apply discount if applicable
        if (params.discountCode) {
            const discount = await context.getRecord('Discount', params.discountCode);
            if (discount) {
                total = total * (1 - discount.percentage / 100);
            }
        }

        // Update order total
        await context.updateRecord('Order', params.orderId, {
            total: total
        });

        return { success: true, total: total };

    } catch (error) {
        return { success: false, error: error.message };
    }
};

SENDMAIL Actions

Send email notifications with templates.

Configuration

  • Recipients - Who receives the email
  • Template - Email template with variables
  • Subject - Email subject line
  • From - Sender address

Template Variables

Use template variables to include dynamic data:

Subject: Order {{order.number}} Confirmation

Dear {{customer.name}},

Your order #{{order.number}} has been confirmed.

Items:
{{#each items}}
  - {{this.name}}: {{this.quantity}} x {{this.price}}
{{/each}}

Total: {{order.total}}

Thank you for your business!

WEBHOOK Actions

Call external APIs when events occur.

Configuration

  • URL - External API endpoint
  • Method - HTTP method
  • Headers - Request headers (authentication, content type)
  • Payload - Data to send

Example: Notify External System

WEBHOOK: Notify Fulfillment
URL: https://fulfillment.example.com/orders
Method: POST
Headers:
  - Authorization: Bearer {{config.fulfillment_api_key}}
  - Content-Type: application/json
Payload:
  {
    "order_id": "{{order.id}}",
    "items": {{items}},
    "shipping_address": "{{customer.address}}"
  }

Action Chaining

Execute multiple actions in sequence:

  1. First action runs
  2. Results pass to next action
  3. Each action can use previous results
  4. Final result returned

Example: Order Processing Chain

Action 1: SCRIPT - Validate inventory
  Output: { available: true, items: [...] }

Action 2: SCRIPT - Create shipment
  Input: Previous output
  Output: { shipment_id: "SH-12345" }

Action 3: SENDMAIL - Confirmation
  Input: Order + shipment details

Action 4: WEBHOOK - Notify warehouse
  Input: Shipment details

Error Handling

In SCRIPT Actions

Always wrap logic in try-catch:

try {
    // Your logic
    return { success: true };
} catch (error) {
    // Log the error
    context.log.error('Operation failed', error);
    return { success: false, error: error.message };
}

Retry Configuration

Configure retry behavior for transient failures:

  • Max Retries - Number of retry attempts
  • Retry Delay - Time between retries
  • Backoff - Increasing delay between retries

Best Practices

Rule Design

  1. Keep rules focused - One rule, one purpose
  2. Use descriptive names - Clearly indicate what the rule does
  3. Add conditions - Filter to avoid unnecessary triggers
  4. Handle errors - Plan for failure scenarios

Action Design

  1. Break into steps - Smaller actions are easier to debug
  2. Validate input - Check data before processing
  3. Add logging - Include debug information
  4. Test thoroughly - Cover edge cases

Performance

  1. Minimize database queries - Batch operations when possible
  2. Use async operations - Don't block on long operations
  3. Set timeouts - Prevent runaway processes
  4. Monitor execution - Track performance metrics

Security

  1. Validate external input - Never trust incoming data
  2. Secure credentials - Use configuration for API keys
  3. Limit permissions - Actions run with appropriate access
  4. Audit sensitive operations - Log important actions

Debugging

Logging

Add logs to track execution:

context.log.info('Processing order', { orderId: params.orderId });
context.log.debug('Items found', { count: items.length });
context.log.error('Failed to process', { error: error.message });

Testing

  1. Use preview mode to test rules
  2. Create test data for various scenarios
  3. Verify all action outputs
  4. Check error handling

Next Steps