# Workflow Editor User Guide

## Overview

The Workflow Editor lets you visually design and configure ticket workflows with a step-by-step approach.

---

## Understanding the Steps

### Step 1-5: Classification (Purple)
**What they do:** Match keywords in ticket title/description to classify the ticket

**Step 1: Branch Routing**
- Determines which team handles the ticket (NOC, SOC, Service Desk)
- Uses classification rules with keywords like "backup", "phishing", "password reset"
- **Config:** `{"rule_type": "branch_routing", "result_field": "branch", "default_value": "service_desk"}`

**Step 2: Ticket Type**
- Classifies as Incident (2) or Service Request (1)
- Keywords: "not working", "stopped working" → Incident
- Keywords: "how do i", "please set up" → Service Request
- **Config:** `{"rule_type": "ticket_type", "result_field": "ticket_type"}`

**Step 3: Issue Classification**
- Determines issue type (Email, AD, Network, Hardware, etc.) and sub-issue type
- Uses 50+ classification rules with specific keywords
- **Config:** `{"rule_type": "issue_classification", "result_field": "issue_type", "result_field_2": "sub_issue_type"}`

**Step 4: Priority**
- Sets ticket priority based on keywords and impact
- Security keywords → Security Event priority
- "multiple users" → Critical priority
- **Config:** `{"rule_type": "priority", "result_field": "priority"}`

**Step 5: Queue Routing**
- Routes to correct queue based on device patterns, priority, etc.
- Critical priority → Level 2 queue
- Workstation devices → Level 1 queue
- **Config:** `{"rule_type": "queue_routing", "result_field": "queue_id"}`

### Step 6: Validation (Yellow)
**What it does:** Checks if all classifications are valid against database picklists

- Validates issue_type exists
- Validates sub_issue_type is a child of issue_type
- Validates priority exists
- Validates queue exists
- **Config:** `{"required_fields": []}`
- **Output:** Sets `context.validation.is_valid` (true/false)

### Step 7: AI Classification (Blue) - Conditional
**What it does:** Uses AI to classify fields that robotic classification missed

- **Only runs if:** Validation failed (condition: `context.validation.is_valid === false`)
- Sends ticket to AI with available picklist options
- AI selects the correct issue type, sub-issue type, etc.
- **Config:** `{"template_purpose": "ambiguous_classification", "skip_if_valid": true}`

### Step 8: AI Title Cleanup (Blue) - Conditional
**What it does:** Cleans up messy ticket titles

- **Only runs if:** Classification indicates title needs cleanup
- Removes email prefixes (Re:, Fw:), ticket numbers, excessive punctuation
- Condenses long titles to max 80 characters
- **Config:** `{"template_purpose": "title_cleanup"}`

### Step 9: Delay (Gray)
**What it does:** Waits before updating Autotask

- Configurable delay (default: 30 seconds)
- Allows time for user to cancel if needed
- Uses template variable for setting: `{{settings.autotask_update_delay_ms}}`
- **Config:** `{"duration_ms": "{{settings.autotask_update_delay_ms}}"}`

### Step 10: Update Ticket (Green)
**What it does:** Writes all accumulated field changes to Autotask

- Takes all changes from previous steps (stored in `context.field_changes`)
- Updates ticket in Autotask via API
- Updates local database copy
- **Config:** `{"use_field_changes": true}`
- **Important:** If this step fails, workflow stops (on_failure: 'stop')

### Step 11: AI Troubleshooting (Blue) - Conditional
**What it does:** Generates troubleshooting steps for incidents

- **Only runs if:** Ticket type is Incident (ticket_type === 2)
- AI generates 3-5 troubleshooting steps
- Creates a ticket note with the steps (TODO: not implemented yet)
- **Config:** `{"template_purpose": "troubleshooting_steps", "create_note": true}`

---

## How to Use the Editor

### Viewing Steps
1. Go to `/admin/workflow/1` (or click Edit on a workflow)
2. **Steps tab** shows all steps in order
3. Each step shows:
   - Step number (e.g., #1)
   - Step name (e.g., "Branch Routing")
   - Step type badge (e.g., "classify")
   - Active/Inactive toggle

### Expanding a Step
1. Click **"Expand"** button on any step
2. You'll see:
   - **Blue help box** explaining what the step does
   - Configuration fields list
   - Example JSON
   - **Step Name** input
   - **On Failure** dropdown
   - **Configuration JSON** textarea

### Editing Configuration
The JSON config defines step behavior:

**Example for "Branch Routing":**
```json
{
  "rule_type": "branch_routing",
  "result_field": "branch",
  "default_value": "service_desk"
}
```

- `rule_type`: Which classification rules to use
- `result_field`: Where to store the result in context
- `default_value`: What to use if no rules match

### Reordering Steps
- Use **↑ ↓ arrows** on the left side of each step
- Steps execute in numerical order (1, 2, 3...)
- Reordering updates the step_order automatically

### Toggling Steps
- **Toggle switch** on each step to enable/disable
- Disabled steps are skipped during execution
- Useful for debugging (e.g., disable AI steps to test faster)

### Saving Changes
- Click **"Save Changes"** button at the top
- Saves both workflow metadata and all steps
- Green toast notification on success

---

## Other Tabs

### Trigger Tab
- **Workflow Name:** Display name
- **Description:** What this workflow does
- **Trigger Event:** ticket.created or ticket.updated
- **Trigger Conditions:** JSON array of conditions that must match
  - Example: Only process tickets in NOC/Service Desk categories
  - Example: Exclude certain creator users or companies

### Test Tab
- **Dry-run testing** (shows endpoint for now)
- Select a ticket ID
- Run workflow without actually updating Autotask
- See step-by-step results and proposed changes

### History Tab
- **Execution history** for this specific workflow
- Shows recent runs with status (completed, failed, skipped)
- Click to see detailed step-by-step breakdown

---

## Tips for Non-Technical Users

**You don't need to write code!** The JSON is just configuration:

1. **To change what a step does:**
   - Expand the step
   - Read the blue help box
   - Copy the example JSON
   - Modify the values you need

2. **To disable a step temporarily:**
   - Just toggle it off (no need to delete)

3. **To test changes:**
   - Save your changes
   - Go to Test tab
   - Run a dry-run to see what would happen

4. **To see if it's working:**
   - Go to History tab
   - Look for recent executions
   - Check if status is "completed" (green)

5. **Common Changes:**
   - **Change delay:** Edit Step 9, change `duration_ms` from 30000 to 60000 (60 seconds)
   - **Disable AI:** Toggle off Steps 7, 8, 11 to use only robotic classification
   - **Change default branch:** Edit Step 1, change `default_value` from "service_desk" to "noc"

---

## Visual Guide

**Collapsed Step:**
```
┌─────────────────────────────────────────┐
│ ↑↓  #1  Branch Routing  [classify]  ✓   │
│                               [Expand]   │
└─────────────────────────────────────────┘
```

**Expanded Step:**
```
┌─────────────────────────────────────────┐
│ ↑↓  #1  Branch Routing  [classify]  ✓   │
│                             [Collapse]   │
├─────────────────────────────────────────┤
│ 📘 What This Step Does                  │
│ Uses keyword-based classification...    │
│                                         │
│ Configuration Fields:                   │
│ • rule_type: branch_routing             │
│ • result_field: branch                  │
│ • default_value: service_desk           │
│                                         │
│ Example: {"rule_type": "branch_r..."}   │
├─────────────────────────────────────────┤
│ Step Name: [Branch Routing______]      │
│                                         │
│ On Failure: [Continue to next step ▼]  │
│                                         │
│ Configuration (JSON):                   │
│ ┌───────────────────────────────────┐  │
│ │ {                                 │  │
│ │   "rule_type": "branch_routing",  │  │
│ │   "result_field": "branch",       │  │
│ │   "default_value": "service_desk" │  │
│ │ }                                 │  │
│ └───────────────────────────────────┘  │
└─────────────────────────────────────────┘
```

---

**Need help?** The blue help box in each expanded step explains everything you need to know!
