# Process Variables System Documentation

## Overview

Process variables serve as the **central nervous system** for data flow and state management in the BPM system. They enable dynamic behavior, external system integration, and stateful execution across multiple user interactions and system boundaries.

## Architecture Components

### 1. VariableManager.vue - Central Variable Management

**Location**: `components/process-flow/VariableManager.vue`

**Primary Functions:**
- **Variable Creation & Management**: Add, edit, delete process variables with comprehensive type support
- **Usage Tracking**: Analyzes where variables are used across all node types (form, API, script, gateway, etc.)
- **Variable Navigation**: Click-to-navigate from variable usage to specific nodes in the process
- **Type Organization**: Groups variables by data type (string, int, decimal, boolean, date, object, etc.)

**Key Features:**
- **14+ Variable Types**: string, int, decimal, boolean, date, datetime, object, array, currency, email, UUID, etc.
- **Deep Usage Analysis**: Scans all node data for variable references in multiple formats:
  - Template placeholders: `{variableName}`, `{{variableName}}`
  - JavaScript references: `${variableName}`, `processVariables.variableName`
  - Direct value assignments and API outputs
- **Cross-Node Detection**: Finds variables in API URLs, form mappings, script code, business rules, notifications

### 2. VariableBrowser.vue - Variable Selection Component

**Location**: `components/process-flow/VariableBrowser.vue`

**Purpose**: Used throughout the process builder for variable selection in node configurations

**Key Features:**
- **Grouped Selection**: Variables organized by type with optgroups
- **Live Preview**: Shows current variable values in selection dropdown
- **Inline Creation**: "+" button to create new variables on-the-fly
- **Type Filtering**: Can restrict to specific variable types
- **Validation**: Checks for variable existence and naming conflicts
- **Rich Type Support**: 20+ variable types including special types (currency, email, UUID, etc.)

**Integration Points:**
- Form node configuration (input/output mappings)
- API node configuration (URL parameters, request body)
- Script node configuration (input/output variables)
- Business rule conditions and actions
- Gateway decision logic
- Notification recipient and content variables

### 3. variableStore.js - Legacy Store

**Location**: `stores/variableStore.js`

**Note**: This appears to be a legacy store with basic functionality. The actual variable management is handled primarily by the `processBuilder` store.

**Features:**
- **Scope Management**: Global vs process-level variables
- **Basic CRUD**: Add, update, delete variables
- **Simple Structure**: Arrays for global and process variables
- **Node Variables**: Input/output tracking for individual nodes

## Variable Lifecycle & Data Flow

### 1. Variable Creation

- **Primary Source**: VariableManager component for explicit creation
- **Secondary Source**: VariableBrowser inline creation during node configuration
- **Auto-Creation**: Form nodes can auto-create variables from mappings (`createVariableFromMapping`)

### 2. Variable Usage Across Node Types

#### Form Nodes (`FormNodeConfiguration.vue`)
- **Input Mappings**: Process variables → Form field pre-filling
- **Output Mappings**: Form submission data → Process variables
- **Field Conditions**: Process variables control field visibility/behavior
- **Assignment Variables**: Dynamic task assignment based on variable values

**Example Configuration:**
```javascript
{
  inputMappings: [
    {
      processVariable: "customerName",
      formField: "name"
    }
  ],
  outputMappings: [
    {
      formField: "email",
      processVariable: "customerEmail"
    }
  ],
  fieldConditions: [
    {
      processVariable: "userType",
      operator: "equals",
      value: "premium",
      targetField: "specialOffers",
      action: "show"
    }
  ]
}
```

#### API Nodes
- **URL Interpolation**: Variables embedded in API endpoints
- **Request Body**: Variables in JSON payloads
- **Headers**: Dynamic authentication tokens/values
- **Output Variables**: API responses stored as process variables
- **Error Handling**: Error data captured in designated variables

**Example Configuration:**
```javascript
{
  apiUrl: "https://api.example.com/users/{userId}",
  requestBody: "{\"name\": \"{customerName}\", \"email\": \"{customerEmail}\"}",
  headers: "{\"Authorization\": \"Bearer {authToken}\"}",
  outputVariable: "apiResponse",
  errorVariable: "apiError"
}
```

#### Script Nodes
- **Input Variables**: Pass process variables to script execution
- **Output Variables**: Script results stored back to process variables
- **Script Code**: Direct variable references in JavaScript code

**Example Configuration:**
```javascript
{
  inputVariables: ["customerAge", "orderAmount"],
  outputVariables: [
    {
      name: "discount",
      type: "decimal",
      description: "Calculated discount amount"
    }
  ],
  scriptCode: `
    const discount = customerAge > 65 ? orderAmount * 0.1 : 0;
    return { discount };
  `
}
```

#### Business Rule Nodes
- **Conditions**: Variables used in rule evaluation logic
- **Actions**: Variables updated based on rule outcomes
- **Complex Logic**: AND/OR conditions with multiple variable checks

#### Gateway/Decision Nodes
- **Decision Logic**: Variables determine process flow paths
- **Condition Evaluation**: Dynamic routing based on variable values

### 3. Variable Reference Patterns

The system supports multiple variable reference formats:

- **Template**: `{variableName}`, `{{variableName}}`
- **JavaScript**: `${variableName}`, `processVariables.variableName`
- **JSON**: Direct string/object references
- **API Integration**: URL parameters, headers, body content

### 4. Variable Tracking & Dependencies

- **Usage Analysis**: Real-time tracking of where variables are used
- **Dependency Management**: Prevents deletion of variables in use
- **Navigation Support**: Click-to-navigate from variable to usage location
- **Reference Counting**: Shows total references per variable

### 5. Process Execution Context

Variables serve as the **data backbone** of process execution:

- **State Management**: Track process state between nodes
- **Data Transformation**: Convert and format data as it flows
- **Decision Making**: Enable dynamic process paths
- **Integration**: Bridge between external systems and process logic
- **User Interaction**: Store and recall user input across process steps

## Variable Types

### Basic Types
- **string**: Text values
- **int**: Whole numbers
- **decimal**: Decimal numbers
- **boolean**: True/False values
- **date**: Date values only
- **datetime**: Date and time values

### Complex Types
- **object**: JSON objects and complex data structures
- **array**: Lists of values
- **map**: Key-value pairs

### Special Types
- **currency**: Monetary values
- **percentage**: Percentage values
- **email**: Email addresses
- **url**: URLs
- **phone**: Phone numbers
- **uuid**: Unique identifiers
- **file**: File references
- **image**: Image references
- **binary**: Binary data

## Form Integration

### Form Node Configuration Steps

The form node configuration provides a comprehensive 4-step process:

#### Step 1: Form Selection
- Select existing forms or create new ones
- Integration with FormSelector component

#### Step 2: Form Data Mapping
- **Input Mappings**: Process variables → Form field pre-filling
- **Output Mappings**: Form submission data → Process variables
- Bidirectional data flow configuration

#### Step 3: Field Conditions
- Configure conditional field behavior based on process variables
- Supported operators: equals, not_equals, is_true, is_false, is_empty, etc.
- Actions: readonly, hide, required, optional, show, enable

#### Step 4: Task Assignment
- **Public**: Anyone can complete
- **Specific Users**: Select individual users
- **Role-based**: Assign to user roles
- **Dynamic**: Use process variables to determine assignee

## API Integration

Variables enable seamless integration with external APIs:

- **Dynamic URLs**: Embed variables in API endpoints
- **Request Customization**: Variables in headers, body, and parameters
- **Response Handling**: Store API responses in process variables
- **Error Management**: Capture and handle API errors

## Best Practices

### Variable Naming
- Use descriptive names (e.g., `customerEmail` instead of `email`)
- Follow camelCase convention
- Avoid spaces and special characters
- Use consistent prefixes for related variables

### Type Selection
- Choose the most specific type for better validation
- Use `object` for complex data structures
- Use `array` for lists of items
- Use special types (email, currency) for semantic clarity

### Scope Management
- Prefer process-level variables for data that persists across nodes
- Use global variables sparingly for truly global data
- Document variable purposes and expected values

### Dependency Management
- Review variable usage before deletion
- Use the usage tracking feature to understand dependencies
- Plan variable lifecycle aligned with process flow

## Development Notes

### Store Integration
Variables are primarily managed through the `processBuilder` store:
- `processStore.addProcessVariable()`
- `processStore.getProcessVariables()`
- `processStore.updateProcessVariable()`
- `processStore.deleteProcessVariable()`

### Component Integration
- VariableBrowser is used throughout node configuration modals
- VariableManager provides comprehensive variable management UI
- Real-time validation and error handling

### Performance Considerations
- Variable usage analysis runs on-demand to avoid performance issues
- Deep object cloning used to prevent reactivity issues
- Efficient grouping and filtering for large variable sets

## Related Documentation

- [Form Builder System](./form-builder-system.md)
- [Process Definition Schema](./json/process-builder/processDefinition.json)
- [Process Variables Example](./json/process-builder/processVariables.json)