# Automation Guide

**Last Updated**: 2026-01-18

Learn how to create and manage automation flows for WhatsApp conversations.

## Overview

Automation flows allow you to define rule-based chatbot logic without AI. Use cases include:

- Welcome messages for new customers
- FAQ auto-responses
- Order confirmation flows
- Lead qualification
- Appointment booking
- Customer support routing

## Core Concepts

### Trigger Types

| Trigger | Description | Example |
|---------|-------------|---------|
| **Keyword** | Message contains specific text | "hi", "help", "price" |
| **Event** | System event occurs | Customer opts in, order created |
| **Schedule** | Time-based activation | Daily at 9 AM, every Monday |

### Flow Steps

Each flow consists of ordered steps. Step types:

**1. Send Message**
- Send text or media message
- Support variables: `{customer_name}`, `{shop_name}`

**2. Quick Reply**
- Present buttons for customer to tap
- Branch to different steps based on choice

**3. Tag Customer**
- Add/remove customer tags
- Use for segmentation

**4. Call Webhook**
- POST data to external URL
- Integrate with CRM, inventory systems

**5. Assign to Agent**
- Route conversation to human agent
- Exit automation

**6. Delay**
- Wait before next step
- Time in seconds/minutes/hours

**7. Conditional Branch**
- If/else logic
- Conditions: tag exists, custom field value, time of day

## Creating a Flow

### Via API

```bash
POST /api/v1/whatsapp/flows
Content-Type: application/json

{
  "shopId": "shop-guid",
  "flowName": "Welcome New Customer",
  "triggerType": "keyword",
  "triggerConfig": {
    "keywords": ["hi", "hello", "start"]
  },
  "steps": [
    {
      "order": 1,
      "action": "send_message",
      "actionConfig": {
        "text": "Welcome to {shop_name}! 👋\n\nHow can we help you today?"
      }
    },
    {
      "order": 2,
      "action": "quick_reply",
      "actionConfig": {
        "text": "Choose an option:",
        "buttons": [
          {"id": "browse", "title": "Browse Products"},
          {"id": "track", "title": "Track Order"},
          {"id": "support", "title": "Talk to Support"}
        ]
      },
      "nextStepMapping": {
        "browse": 3,
        "track": 5,
        "support": 7
      }
    },
    {
      "order": 3,
      "action": "send_message",
      "actionConfig": {
        "text": "Visit our catalog: https://shop.example.com"
      }
    }
  ]
}
```

### Response

```json
{
  "success": true,
  "data": {
    "flowId": "flow-guid",
    "flowName": "Welcome New Customer",
    "isActive": false,
    "createdAt": "2026-01-18T10:00:00Z"
  }
}
```

## Flow Examples

### Example 1: FAQ Bot

**Trigger**: Keywords "price", "cost", "how much"

**Flow**:
1. Send: "Our pricing depends on the product. What are you interested in?"
2. Quick Reply: ["Clothing", "Electronics", "Food"]
3. Conditional:
   - If "Clothing" → Send pricing for clothing
   - If "Electronics" → Send pricing for electronics  
   - If "Food" → Send pricing for food

### Example 2: Appointment Booking

**Trigger**: Keyword "appointment", "booking"

**Flow**:
1. Send: "I can help you book an appointment! 📅"
2. Send: "What service do you need?"
3. Quick Reply: ["Consultation", "Check-up", "Follow-up"]
4. Tag Customer: "appointment-pending"
5. Call Webhook: POST to booking system
6. Delay: 2 seconds (wait for webhook response)
7. Send: "Your appointment is confirmed! You'll receive a reminder."

### Example 3: Order Tracking

**Trigger**: Keyword "track", "order status"

**Flow**:
1. Send: "Please send your order number (e.g., #12345)"
2. (Customer replies with order number)
3. Call Webhook: GET order status from backend
4. Conditional:
   - If order found → Send status + tracking link
   - If not found → Send "Order not found. Please check the number."

## Variables

Use variables in message text for personalization:

### Customer Variables

- `{customer_name}` - Customer's name
- `{customer_phone}` - Customer's WhatsApp number
- `{customer_tags}` - Comma-separated tags

### Shop Variables

- `{shop_name}` - Shop name
- `{shop_url}` - Shop website URL

### Conversation Variables

- `{conversation_id}` - Conversation UUID
- `{message_count}` - Number of messages in conversation

### Custom Variables (from webhook response)

Webhook can return variables:

```json
{
  "variables": {
    "order_status": "Shipped",
    "tracking_number": "ABC123XYZ"
  }
}
```

Use in next step:
```
Your order is {order_status}. Track it here: {tracking_number}
```

## Conditions

### Supported Conditions

**Tag Exists**
```json
{
  "type": "tag_exists",
  "tag": "vip-customer"
}
```

**Custom Field Equals**
```json
{
  "type": "custom_field_equals",
  "field": "city",
  "value": "Hanoi"
}
```

**Time of Day**
```json
{
  "type": "time_of_day",
  "start": "09:00",
  "end": "17:00",
  "timezone": "Asia/Ho_Chi_Minh"
}
```

**Day of Week**
```json
{
  "type": "day_of_week",
  "days": ["monday", "tuesday", "wednesday"]
}
```

**Message Contains**
```json
{
  "type": "message_contains",
  "text": "urgent",
  "case_sensitive": false
}
```

### Combining Conditions

Use AND/OR logic:

```json
{
  "type": "and",
  "conditions": [
    {"type": "tag_exists", "tag": "vip-customer"},
    {"type": "time_of_day", "start": "00:00", "end": "23:59"}
  ]
}
```

## Activating a Flow

```bash
POST /api/v1/whatsapp/flows/{flowId}/activate
```

**Response**:
```json
{
  "success": true,
  "data": {
    "flowId": "flow-guid",
    "isActive": true,
    "activatedAt": "2026-01-18T10:05:00Z"
  }
}
```

## Priority

When multiple flows match, priority determines which executes:

1. **Explicit keyword match** (highest priority)
2. **Event triggers**
3. **Scheduled triggers** (lowest priority)

Set priority when creating flow:

```json
{
  "flowName": "VIP Customer Welcome",
  "priority": 100,
  ...
}
```

Higher number = higher priority (default: 50)

## Testing a Flow

### Test Mode

Enable test mode to see execution without sending actual messages:

```bash
POST /api/v1/whatsapp/flows/{flowId}/test
Content-Type: application/json

{
  "shopId": "shop-guid",
  "customerWaId": "84901234567",
  "simulatedMessage": "hi"
}
```

**Response**:
```json
{
  "success": true,
  "data": {
    "matched": true,
    "executedSteps": [
      {"step": 1, "action": "send_message", "result": "Would send: Welcome..."},
      {"step": 2, "action": "quick_reply", "result": "Would show buttons"}
    ]
  }
}
```

### Debug Logs

View flow execution history:

```bash
GET /api/v1/whatsapp/flows/{flowId}/executions?limit=20
```

## Best Practices

### 1. Keep Flows Simple

- Max 10 steps per flow
- Avoid deep nesting of conditions
- Break complex flows into multiple smaller flows

### 2. Provide Exit Points

Always give customers a way to:
- Talk to human agent ("support", "help")
- Start over ("restart", "menu")
- Opt out ("stop", "unsubscribe")

### 3. Handle Unknown Inputs

Add a fallback step:
```json
{
  "order": 99,
  "action": "send_message",
  "actionConfig": {
    "text": "I didn't understand. Reply 'menu' to see options or 'support' to talk to an agent."
  }
}
```

### 4. Use Delays Wisely

- After webhook calls: 2-5 seconds
- Between messages: 1-2 seconds (more natural)
- Avoid delays > 10 seconds (customer may leave)

### 5. A/B Testing

Create two versions of a flow:

- Flow A: Send message variant A
- Flow B: Send message variant B

Route 50% traffic to each, measure:
- Response rate
- Conversion rate
- Time to resolution

## Limitations

- Max 50 active flows per shop
- Max 20 steps per flow
- Max 10 quick reply buttons per message
- Webhook timeout: 10 seconds
- No loops (anti-cycle validation)

## Troubleshooting

### Flow Not Triggering

**Check**:
1. Flow is activated (`isActive: true`)
2. Trigger keyword matches exactly (case-insensitive)
3. No higher-priority flow is matching first
4. Customer has not opted out

### Webhook Failing

**Check**:
1. Webhook URL is accessible (HTTPS required)
2. Webhook responds within 10 seconds
3. Response status code is 200
4. Response JSON is valid

### Variables Not Replacing

**Check**:
1. Variable syntax is correct: `{variable_name}`
2. Variable is defined (customer_name exists for customer)
3. Webhook returned expected variables

## Next Steps

- [AI Chatbot Guide](AI_CHATBOT_GUIDE.md) - Combine with AI for hybrid approach
- [API Documentation](API.md) - Full API reference
- [Architecture](ARCHITECTURE.md) - Understanding the automation engine

## Resources

- [Flow Builder UI](https://platform.goodgo.com/whatsapp/flows) (if available)
- [Webhook Integration Guide](WEBHOOK_INTEGRATION.md)
