Rules and Actions
Automate business processes with Rules and Actions
Rules and Actions Example
Learn to automate business processes using Appivo's Rules and Actions system.
What You'll Build
An automated order processing system with:
- Email notifications on new orders
- Inventory updates when orders ship
- Scheduled daily reports
- Integration with external fulfillment
Prerequisites
- Completed the CRUD Operations example
- Understanding of models and data operations
Understanding Rules and Actions
Rules Define WHEN
Rules are triggers that start automation:
| Rule Type | Triggered By |
|---|---|
| DATA | Model changes (create, update, delete) |
| SCHEDULED | Time intervals |
| REST | External API calls |
| Incoming emails | |
| MANUAL | User button click |
Actions Define WHAT
Actions are the operations that execute:
| Action Type | Purpose |
|---|---|
| SCRIPT | Custom JavaScript logic |
| SENDMAIL | Send email notifications |
| SENDSMS | Send text messages |
| WEBHOOK | Call external APIs |
| SENDPUSH | Mobile push notifications |
Example 1: New Order Notification
Send email when a new order is created.
Create the Rule
Rule: Notify on New Order
Type: DATA
Trigger: When Order is created
Add SENDMAIL Action
Action: Send Order Confirmation
Type: SENDMAIL
To: {{order.customer_email}}
Subject: "Order Confirmation - {{order.order_number}}"
Template: order_confirmation
Data:
order_number: {{order.order_number}}
customer_name: {{order.customer_name}}
items: {{order.items}}
total: {{order.total}}
Create Email Template
Template: order_confirmation
---
Dear {{customer_name}},
Thank you for your order #{{order_number}}.
Your order total: ${{total}}
We'll notify you when it ships.
Best regards,
The Team
Example 2: Inventory Update on Ship
Update inventory when order status changes to "Shipped".
Create the Rule
Rule: Update Inventory on Ship
Type: DATA
Trigger: When Order is updated
Condition: status changed to "Shipped"
Add SCRIPT Action
Action: Reduce Inventory
Type: SCRIPT
exports.execute = async function(context, params) {
const order = params.record;
// Only process if status changed to Shipped
if (order.status !== 'Shipped') {
return { success: true };
}
// Get order items
const items = await context.find('OrderItem', {
filter: { order_id: order.id }
});
// Update inventory for each item
for (const item of items.records) {
const product = await context.getRecord('Product', item.product_id);
await context.updateRecord('Product', product.id, {
stock: product.stock - item.quantity
});
}
return { success: true };
};
Example 3: Scheduled Daily Report
Generate a daily sales report.
Create the Rule
Rule: Daily Sales Report
Type: SCHEDULED
Schedule: Every day at 6:00 AM
Add SCRIPT Action
Action: Generate Report
Type: SCRIPT
exports.execute = async function(context, params) {
// Get yesterday's date range
const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const startOfDay = new Date(yesterday.setHours(0, 0, 0, 0));
const endOfDay = new Date(yesterday.setHours(23, 59, 59, 999));
// Get yesterday's orders
const orders = await context.find('Order', {
filter: {
created_at: {
$gte: startOfDay,
$lte: endOfDay
},
status: { $ne: 'Cancelled' }
}
});
// Calculate totals
let totalSales = 0;
let orderCount = orders.records.length;
for (const order of orders.records) {
totalSales += order.total;
}
// Create report record
await context.createRecord('DailyReport', {
report_date: yesterday,
order_count: orderCount,
total_sales: totalSales,
average_order: orderCount > 0 ? totalSales / orderCount : 0
});
return {
success: true,
message: `Report generated: ${orderCount} orders, $${totalSales} total`
};
};
Add SENDMAIL Action
Send the report to managers:
Action: Email Report
Type: SENDMAIL
To: managers@company.com
Subject: "Daily Sales Report - {{date}}"
Template: daily_report
Example 4: External API Integration
Send orders to fulfillment system.
Create the Rule
Rule: Send to Fulfillment
Type: DATA
Trigger: When Order status changes to "Processing"
Add WEBHOOK Action
Action: Notify Fulfillment
Type: WEBHOOK
URL: https://fulfillment.example.com/api/orders
Method: POST
Headers:
Authorization: Bearer {{config.fulfillment_api_key}}
Content-Type: application/json
Body:
{
"order_id": "{{order.order_number}}",
"customer": {
"name": "{{order.customer_name}}",
"address": "{{order.shipping_address}}"
},
"items": {{order.items}},
"priority": "{{order.priority}}"
}
Example 5: Manual Approval Workflow
Require manager approval for large orders.
Create the Rule
Rule: Large Order Approval
Type: DATA
Trigger: When Order is created
Condition: total > 10000
Add SCRIPT Action
exports.execute = async function(context, params) {
const order = params.record;
// Mark order as pending approval
await context.updateRecord('Order', order.id, {
status: 'Pending Approval',
requires_approval: true
});
// Create approval task
await context.createRecord('ApprovalTask', {
order_id: order.id,
type: 'Large Order',
amount: order.total,
status: 'Pending',
assigned_to: 'manager_role'
});
return { success: true };
};
Add SENDMAIL Action
Action: Notify Manager
Type: SENDMAIL
To: managers@company.com
Subject: "Approval Required - Order {{order.order_number}}"
Template: approval_required
Example 6: Chained Rules
Run multiple rules in sequence.
Primary Rule
Rule: Process Order
Type: DATA
Trigger: When Order is created
Chain: After completion, trigger "Check Inventory"
Chained Rule
Rule: Check Inventory
Type: CHAIN
Triggered by: Process Order rule
Action: SCRIPT
- Check if items in stock
- If not, create reorder request
Complete Workflow: Order Processing
Order Created
│
├── Rule: Validate Order
│ └── SCRIPT: Check required fields, validate items
│
├── Rule: Notify Customer
│ └── SENDMAIL: Order confirmation
│
├── Rule: Large Order Check
│ └── If total > $10,000
│ ├── SCRIPT: Mark pending approval
│ └── SENDMAIL: Notify manager
│
└── Rule: Send to Fulfillment
└── WEBHOOK: External fulfillment API
Order Status → "Shipped"
│
├── Rule: Update Inventory
│ └── SCRIPT: Reduce stock levels
│
├── Rule: Notify Customer
│ └── SENDMAIL: Shipping confirmation
│
└── Rule: Push Notification
└── SENDPUSH: Mobile app notification
Daily at 6 AM
│
└── Rule: Daily Report
├── SCRIPT: Generate report data
└── SENDMAIL: Send to managers
Rule Configuration Options
Conditions
Add conditions to control when rules execute:
Rule: Process VIP Orders First
Condition: customer.tier = "VIP"
Error Handling
Configure what happens when actions fail:
Rule Configuration:
On Error:
- Retry (3 attempts with backoff)
- Log error
- Send alert to admin
Execution Order
Control action execution:
Actions:
1. Validate (must succeed)
2. Update Record (depends on 1)
3. Send Email (runs in parallel)
4. Call Webhook (runs in parallel)
Best Practices
Rule Design
- Keep rules focused on one purpose
- Use meaningful names
- Add conditions to limit execution
- Document complex logic
Action Scripts
- Handle errors gracefully
- Return meaningful messages
- Avoid infinite loops
- Use async/await properly
Performance
- Don't trigger unnecessary rules
- Batch operations when possible
- Use scheduled rules for heavy tasks
- Monitor execution times
Testing
- Test in DEVELOPMENT environment
- Check all conditions
- Verify email templates
- Test error scenarios
Next Steps
- AI Integration - Add intelligent automation
- Integrations - External API connections
- Rules and Actions Guide - Complete reference
- API Integration Guide - Advanced integration patterns