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 Type | Trigger | Use Case |
|---|---|---|
| DATA | Record create/update/delete | React to data changes |
| SCHEDULED | Specific times | Recurring tasks, reports |
| REST | External API calls | Integration endpoints |
| TIMEBASED | Time intervals | Polling, periodic checks |
| MESSAGE | Messages received | Message processing |
| Incoming emails | Email processing | |
| SMS | Incoming SMS | SMS processing |
| MANUAL | User action | On-demand operations |
| CHAIN | Other rule completes | Multi-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
- First rule executes and completes
- CHAIN rule triggers automatically
- 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 Type | Purpose | Example |
|---|---|---|
| SCRIPT | Custom JavaScript code | Complex calculations |
| SENDMAIL | Send emails | Notifications, reports |
| SENDSMS | Send text messages | Alerts, verification |
| SENDPUSH | Push notifications | Mobile alerts |
| WEBHOOK | Call external APIs | Integrations |
| SERVER | Server operations | System tasks |
| SSH | Remote commands | Server management |
| FTP | File transfers | Data exchange |
| SFTP | Secure file transfers | Secure 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:
- First action runs
- Results pass to next action
- Each action can use previous results
- 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
- Keep rules focused - One rule, one purpose
- Use descriptive names - Clearly indicate what the rule does
- Add conditions - Filter to avoid unnecessary triggers
- Handle errors - Plan for failure scenarios
Action Design
- Break into steps - Smaller actions are easier to debug
- Validate input - Check data before processing
- Add logging - Include debug information
- Test thoroughly - Cover edge cases
Performance
- Minimize database queries - Batch operations when possible
- Use async operations - Don't block on long operations
- Set timeouts - Prevent runaway processes
- Monitor execution - Track performance metrics
Security
- Validate external input - Never trust incoming data
- Secure credentials - Use configuration for API keys
- Limit permissions - Actions run with appropriate access
- 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
- Use preview mode to test rules
- Create test data for various scenarios
- Verify all action outputs
- Check error handling
Next Steps
- AI Agents - Add intelligent automation to your actions
- Data Modeling - Design your data structure
- User Interfaces - Build your application UI
- API Integration - Connect external systems