# Process Flow Creation Guide

## Overview
This guide explains how to create process flows using the node-based process builder. Process flows are defined as JSON structures containing nodes and edges that represent business processes.

## Process Definition Structure

### Root Structure
```json
{
  "nodes": [...],
  "edges": [...],
  "viewport": {
    "x": 0,
    "y": 0,
    "zoom": 1
  }
}
```

## Node Types

### 1. Start Node
**Purpose**: Entry point for the process
```json
{
  "id": "start-{timestamp}",
  "type": "start",
  "label": "Start",
  "position": {"x": 210, "y": 180},
  "data": {
    "label": "Start",
    "description": "Process start point"
  }
}
```

### 2. Form Node
**Purpose**: User task requiring form completion
```json
{
  "id": "form-{timestamp}",
  "type": "form",
  "label": "Form Name",
  "position": {"x": 405, "y": 135},
  "data": {
    "label": "Borang Maklumat Peribadi",
    "formId": 1,
    "formName": "Borang Maklumat Peribadi",
    "formUuid": "9f08fc8f-b170-478a-85fd-fa3364401533",
    "description": "Form: Borang Maklumat Peribadi",
    "assignmentType": "public|role|user",
    "assignedRoles": [],
    "assignedUsers": [],
    "assignmentVariable": "",
    "assignmentVariableType": "user_id",
    "inputMappings": [
      {
        "formField": "reference_number",
        "processVariable": "applicationId"
      }
    ],
    "outputMappings": [
      {
        "formField": "text_3",
        "processVariable": "text3"
      }
    ],
    "fieldConditions": []
  }
}
```

**Assignment Types:**
- `public`: Anyone can complete the form
- `role`: Assigned to specific roles
- `user`: Assigned to specific users

### 3. API Node
**Purpose**: External API calls
```json
{
  "id": "api-{timestamp}",
  "type": "api",
  "label": "Submit Profile API",
  "position": {"x": 600, "y": 135},
  "data": {
    "label": "Submit Profile API",
    "description": "Submit user profile to external system",
    "apiUrl": "https://jsonplaceholder.typicode.com/posts",
    "apiMethod": "GET|POST|PUT|DELETE|PATCH",
    "headers": "{ \"Content-Type\": \"application/json\" }",
    "requestBody": "{\n  \"applicantName\": \"{text3}\",\n  \"idType\": \"{select1}\"\n}",
    "outputVariable": "apiResponse",
    "errorVariable": "apiError",
    "continueOnError": false
  }
}
```

**HTTP Methods**: GET, POST, PUT, DELETE, PATCH
**Variable References**: Use `{variableName}` syntax in URL, headers, and body

### 4. Script Node
**Purpose**: Data processing and transformation
```json
{
  "id": "script-{timestamp}",
  "type": "script",
  "label": "Process API Response",
  "position": {"x": 800, "y": 135},
  "data": {
    "label": "Process API Response",
    "description": "Transform API response for document verification step",
    "scriptLanguage": "javascript",
    "scriptCode": "// Extract important data from API response\nconst apiData = processVariables.apiResponse;\n\nif (apiData && apiData.data) {\n  processVariables.applicationId = apiData.data.id || 'APP-' + Date.now();\n}",
    "inputVariables": ["apiResponse", "text3", "radioPendidikan"],
    "outputVariables": [
      {
        "name": "applicationId",
        "type": "string",
        "description": "Generated application ID"
      }
    ],
    "errorVariable": "scriptError",
    "continueOnError": false
  }
}
```

**Script Languages**: javascript, python
**Variable Access**: Use `processVariables.variableName` to access/set variables

### 5. Decision Node (Gateway)
**Purpose**: Conditional branching
```json
{
  "id": "gateway-{timestamp}",
  "type": "gateway",
  "label": "Check Documents",
  "position": {"x": 700, "y": 200},
  "data": {
    "label": "Check Documents",
    "description": "Route based on document requirements",
    "gatewayType": "exclusive",
    "conditions": [
      {
        "id": "condition-1",
        "label": "Documents Required",
        "variable": "documentsRequired",
        "operator": "equals",
        "value": true,
        "targetNode": "form-verification"
      },
      {
        "id": "condition-2",
        "label": "No Documents",
        "variable": "documentsRequired",
        "operator": "equals",
        "value": false,
        "targetNode": "end-approved"
      }
    ],
    "defaultPath": "end-rejected"
  }
}
```

**Gateway Types**: exclusive, inclusive, parallel
**Operators**: equals, not_equals, greater_than, less_than, contains

### 6. Business Rule Node
**Purpose**: Complex business logic evaluation
```json
{
  "id": "business-rule-{timestamp}",
  "type": "business-rule",
  "label": "Eligibility Rules",
  "position": {"x": 900, "y": 200},
  "data": {
    "label": "Eligibility Rules",
    "description": "Evaluate application eligibility",
    "ruleGroups": [
      {
        "id": "group-1",
        "name": "Age Requirements",
        "operator": "AND",
        "conditions": [
          {
            "variable": "applicantAge",
            "operator": "greater_than",
            "value": 18
          }
        ],
        "actions": [
          {
            "type": "set_variable",
            "variable": "ageEligible",
            "value": true
          }
        ]
      }
    ],
    "outputVariable": "ruleResult",
    "errorVariable": "ruleError"
  }
}
```

### 7. Notification Node
**Purpose**: Send notifications
```json
{
  "id": "notification-{timestamp}",
  "type": "notification",
  "label": "Send Approval Email",
  "position": {"x": 1000, "y": 200},
  "data": {
    "label": "Send Approval Email",
    "description": "Notify applicant of approval",
    "notificationType": "email|sms|push",
    "recipientType": "variable|role|user|email",
    "recipientValue": "applicantEmail",
    "subject": "Application Approved - {applicationId}",
    "message": "Dear {applicantName},\n\nYour application {applicationId} has been approved.",
    "template": "approval-template",
    "errorVariable": "notificationError"
  }
}
```

**Notification Types**: email, sms, push, internal
**Recipient Types**: variable, role, user, email

### 8. End Node
**Purpose**: Process termination
```json
{
  "id": "end-{timestamp}",
  "type": "end",
  "label": "End",
  "position": {"x": 1200, "y": 180},
  "data": {
    "label": "End",
    "description": "Process completion point"
  }
}
```

## Edges (Connections)

### Basic Edge
```json
{
  "id": "{sourceId}-{targetId}-{timestamp}",
  "source": "start-1751870920411",
  "target": "form-1751870928350",
  "type": "smoothstep",
  "animated": true,
  "label": "",
  "data": {}
}
```

### Conditional Edge (from Gateway)
```json
{
  "id": "gateway-condition-{timestamp}",
  "source": "gateway-1751870920411",
  "target": "form-1751870928350",
  "type": "smoothstep",
  "animated": true,
  "label": "Documents Required",
  "data": {
    "condition": "documentsRequired == true"
  }
}
```

## Process Variables

### Variable Definition Structure
Process variables are stored as a JSON object where each variable has a specific structure:

```json
{
  "variableName": {
    "name": "variableName",
    "type": "string|number|boolean|object|array",
    "scope": "global|local",
    "value": null,
    "description": "Variable description"
  }
}
```

### Complete Process Variables Format
Based on the actual database structure, here's the complete format for process variables:

```json
{
  "text3": {
    "name": "text3",
    "type": "string",
    "scope": "global",
    "value": "Ahmad Bin Ali",
    "description": "Form data from text_3 in Borang Maklumat Peribadi"
  },
  "select1": {
    "name": "select1",
    "type": "string",
    "scope": "global",
    "value": "staff",
    "description": "Form data from select_1 in Borang Maklumat Peribadi"
  },
  "apiResponse": {
    "name": "apiResponse",
    "type": "object",
    "scope": "global",
    "value": {
      "data": {
        "id": "APP-2024-001234",
        "score": 85,
        "status": "pending_verification",
        "profileId": "PROF-567890",
        "riskLevel": "low",
        "documentCount": 3,
        "submissionDate": "2024-01-15T10:30:00Z"
      },
      "status": "success",
      "message": "Profile submitted successfully"
    },
    "description": "API response from Submit Profile Data"
  },
  "radioJantina": {
    "name": "radioJantina",
    "type": "string",
    "scope": "global",
    "value": "Lelaki",
    "description": "Form data from radio_jantina in Borang Maklumat Peribadi"
  },
  "documentsRequired": {
    "name": "documentsRequired",
    "type": "boolean",
    "scope": "global",
    "value": true,
    "description": "Whether documents verification is required"
  },
  "applicationId": {
    "name": "applicationId",
    "type": "string",
    "scope": "global",
    "value": "APP-1751871528249",
    "description": "Generated application ID from script processing"
  },
  "apiError": {
    "name": "apiError",
    "type": "object",
    "scope": "global",
    "value": null,
    "description": "API error from Submit Profile Data"
  },
  "scriptError": {
    "name": "scriptError",
    "type": "object",
    "scope": "global",
    "value": null,
    "description": "Error information from script execution"
  }
}
```

### Variable Types and Examples

#### String Variables
```json
{
  "applicantName": {
    "name": "applicantName",
    "type": "string",
    "scope": "global",
    "value": "Ahmad Bin Ali",
    "description": "Applicant's full name"
  },
  "verificationLevel": {
    "name": "verificationLevel",
    "type": "string",
    "scope": "global",
    "value": "enhanced",
    "description": "Level of verification required (standard/enhanced)"
  }
}
```

#### Number Variables
```json
{
  "profileScore": {
    "name": "profileScore",
    "type": "number",
    "scope": "global",
    "value": 85,
    "description": "Profile evaluation score from API"
  },
  "requestAmount": {
    "name": "requestAmount",
    "type": "number",
    "scope": "global",
    "value": 1500.50,
    "description": "Requested loan amount"
  }
}
```

#### Boolean Variables
```json
{
  "documentsRequired": {
    "name": "documentsRequired",
    "type": "boolean",
    "scope": "global",
    "value": true,
    "description": "Whether documents verification is required"
  },
  "nextStepReady": {
    "name": "nextStepReady",
    "type": "boolean",
    "scope": "global",
    "value": false,
    "description": "Whether ready for next step in process"
  }
}
```

#### Object Variables
```json
{
  "apiResponse": {
    "name": "apiResponse",
    "type": "object",
    "scope": "global",
    "value": {
      "data": {
        "id": "APP-2024-001234",
        "score": 85,
        "status": "pending_verification"
      },
      "status": "success",
      "message": "Profile submitted successfully"
    },
    "description": "Complete API response object"
  },
  "userProfile": {
    "name": "userProfile",
    "type": "object",
    "scope": "global",
    "value": {
      "name": "Ahmad Bin Ali",
      "email": "ahmad@example.com",
      "phone": "+60123456789",
      "address": {
        "street": "Jalan Bangsar",
        "city": "Kuala Lumpur",
        "postcode": "59000"
      }
    },
    "description": "User profile information"
  }
}
```

#### Array Variables
```json
{
  "assignedRoles": {
    "name": "assignedRoles",
    "type": "array",
    "scope": "global",
    "value": ["manager", "supervisor", "admin"],
    "description": "List of roles assigned to task"
  },
  "documentTypes": {
    "name": "documentTypes",
    "type": "array",
    "scope": "global",
    "value": [
      {
        "type": "IC",
        "required": true,
        "status": "pending"
      },
      {
        "type": "Passport",
        "required": false,
        "status": "not_required"
      }
    ],
    "description": "Array of document requirement objects"
  }
}
```

#### Date Variables
```json
{
  "dateMasukislam": {
    "name": "dateMasukislam",
    "type": "string",
    "scope": "global",
    "value": "2020-05-15",
    "description": "Islam conversion date in YYYY-MM-DD format"
  },
  "verificationDate": {
    "name": "verificationDate",
    "type": "string",
    "scope": "global",
    "value": "2024-01-15T10:30:00Z",
    "description": "ISO 8601 formatted verification timestamp"
  }
}
```

### Variable Scopes
- **global**: Available throughout the entire process
- **local**: Available only within the current node/task

### Variable Naming Conventions
- Use **camelCase** for consistency (e.g., `applicantName`, `verificationLevel`)
- Form field mappings often use **snake_case** to match form field names
- Keep names descriptive and meaningful
- Avoid spaces and special characters
- Use consistent prefixes for related variables

### Variable Usage Patterns

#### In API Calls
```json
{
  "apiUrl": "https://api.example.com/users/{userId}/profile",
  "headers": "{ \"Authorization\": \"Bearer {apiToken}\", \"Content-Type\": \"application/json\" }",
  "requestBody": "{\n  \"name\": \"{applicantName}\",\n  \"score\": {profileScore},\n  \"verified\": {documentsRequired}\n}"
}
```

#### In Script Nodes
```javascript
// Accessing variables
const applicantName = processVariables.applicantName;
const score = processVariables.profileScore;
const apiData = processVariables.apiResponse;

// Setting variables
processVariables.applicationId = 'APP-' + Date.now();
processVariables.verificationLevel = score > 80 ? 'enhanced' : 'standard';
processVariables.nextStepReady = true;

// Working with objects
if (processVariables.apiResponse && processVariables.apiResponse.data) {
  processVariables.externalId = processVariables.apiResponse.data.id;
}
```

#### In Gateway Conditions
```json
{
  "conditions": [
    {
      "variable": "profileScore",
      "operator": "greater_than",
      "value": 75
    },
    {
      "variable": "documentsRequired",
      "operator": "equals",
      "value": true
    },
    {
      "variable": "verificationLevel",
      "operator": "equals",
      "value": "enhanced"
    }
  ]
}
```

#### In Notifications
```json
{
  "subject": "Application {applicationId} - Status Update",
  "message": "Dear {applicantName},\n\nYour application {applicationId} has been processed.\nScore: {profileScore}\nStatus: {verificationLevel}\n\nThank you."
}
```

#### In Form Mappings
```json
{
  "inputMappings": [
    {
      "formField": "reference_number",
      "processVariable": "applicationId"
    },
    {
      "formField": "applicant_name",
      "processVariable": "applicantName"
    }
  ],
  "outputMappings": [
    {
      "formField": "verification_result",
      "processVariable": "verificationResult"
    },
    {
      "formField": "verification_notes",
      "processVariable": "verificationNotes"
    }
  ]
}
```

### Error Variables
Always include error variables for nodes that can fail:

```json
{
  "apiError": {
    "name": "apiError",
    "type": "object",
    "scope": "global",
    "value": null,
    "description": "API error from Submit Profile Data"
  },
  "scriptError": {
    "name": "scriptError",
    "type": "object",
    "scope": "global",
    "value": null,
    "description": "Error information from script execution"
  },
  "verificationApiError": {
    "name": "verificationApiError",
    "type": "object",
    "scope": "global",
    "value": null,
    "description": "API error from verification submission"
  }
}
```

### Variable Best Practices
1. **Initialize with null values** for variables that will be set during process execution
2. **Provide clear descriptions** explaining the variable's purpose and source
3. **Use consistent typing** - don't mix string and number types for the same concept
4. **Group related variables** with similar naming patterns
5. **Plan for error handling** by including error variables
6. **Document data formats** especially for dates and complex objects

## Process Settings

### Basic Settings
```json
{
  "owner": "",
  "category": "HR",
  "priority": "normal|high|low",
  "processType": "standard|template",
  "allowParallel": false,
  "requireApproval": false,
  "enableAuditTrail": true,
  "sendNotifications": true,
  "executionPermission": "public|authenticated|role",
  "modificationPermission": "owner|managers|admin"
}
```

### Advanced Settings
```json
{
  "autoTimeout": 24,
  "maxExecutionTime": 60,
  "dataPersistence": "short_term|long_term|permanent",
  "dataRetentionPolicy": "",
  "enableErrorRecovery": true,
  "encryptSensitiveData": false,
  "logVariableChanges": true,
  "allowedRoles": ""
}
```

## Complete Example Process

### Simple Approval Process
```json
{
  "nodes": [
    {
      "id": "start-001",
      "type": "start",
      "label": "Start",
      "position": {"x": 100, "y": 100},
      "data": {"label": "Start", "description": "Begin approval process"}
    },
    {
      "id": "form-application",
      "type": "form",
      "label": "Application Form",
      "position": {"x": 300, "y": 100},
      "data": {
        "formId": 1,
        "assignmentType": "public",
        "outputMappings": [
          {"formField": "applicant_name", "processVariable": "applicantName"},
          {"formField": "amount", "processVariable": "requestAmount"}
        ]
      }
    },
    {
      "id": "gateway-amount",
      "type": "gateway",
      "label": "Check Amount",
      "position": {"x": 500, "y": 100},
      "data": {
        "gatewayType": "exclusive",
        "conditions": [
          {
            "variable": "requestAmount",
            "operator": "greater_than",
            "value": 1000,
            "targetNode": "form-manager-approval"
          }
        ],
        "defaultPath": "notification-auto-approve"
      }
    },
    {
      "id": "form-manager-approval",
      "type": "form",
      "label": "Manager Approval",
      "position": {"x": 500, "y": 250},
      "data": {
        "formId": 2,
        "assignmentType": "role",
        "assignedRoles": ["manager"],
        "inputMappings": [
          {"formField": "applicant", "processVariable": "applicantName"},
          {"formField": "amount", "processVariable": "requestAmount"}
        ]
      }
    },
    {
      "id": "notification-auto-approve",
      "type": "notification",
      "label": "Auto Approval",
      "position": {"x": 700, "y": 100},
      "data": {
        "notificationType": "email",
        "recipientType": "variable",
        "recipientValue": "applicantEmail",
        "subject": "Application Approved",
        "message": "Your request for {requestAmount} has been automatically approved."
      }
    },
    {
      "id": "end-001",
      "type": "end",
      "label": "End",
      "position": {"x": 900, "y": 100},
      "data": {"label": "End", "description": "Process completed"}
    }
  ],
  "edges": [
    {"id": "e1", "source": "start-001", "target": "form-application", "type": "smoothstep"},
    {"id": "e2", "source": "form-application", "target": "gateway-amount", "type": "smoothstep"},
    {"id": "e3", "source": "gateway-amount", "target": "form-manager-approval", "type": "smoothstep", "label": "> 1000"},
    {"id": "e4", "source": "gateway-amount", "target": "notification-auto-approve", "type": "smoothstep", "label": "≤ 1000"},
    {"id": "e5", "source": "form-manager-approval", "target": "end-001", "type": "smoothstep"},
    {"id": "e6", "source": "notification-auto-approve", "target": "end-001", "type": "smoothstep"}
  ],
  "viewport": {"x": 0, "y": 0, "zoom": 1}
}
```

## Best Practices

### Node Naming
- Use descriptive labels that explain the purpose
- Include timestamps in IDs for uniqueness
- Keep descriptions clear and concise

### Variable Management
- Use consistent naming conventions (camelCase)
- Document all variables with descriptions
- Group related variables logically

### Flow Design
- Start simple and add complexity gradually
- Use gateways for clear decision points
- Include error handling paths
- Test each node configuration

### Error Handling
- Always define error variables for API and script nodes
- Use `continueOnError` appropriately
- Include notification nodes for error scenarios
- Plan alternative paths for failures

### Performance Considerations
- Minimize API calls in loops
- Use appropriate timeout values
- Consider parallel execution where possible
- Keep script code efficient

## Common Patterns

### Data Collection → Processing → Approval
1. Form node for data collection
2. Script node for data validation/transformation
3. Gateway for routing based on criteria
4. Form node for approval tasks
5. Notification for status updates

### External Integration
1. Form node for user input
2. Script node for data preparation
3. API node for external system call
4. Script node for response processing
5. Gateway for success/failure routing

### Multi-level Approval
1. Form node for request submission
2. Gateway for routing based on amount/type
3. Multiple form nodes for different approval levels
4. Parallel gateways for concurrent approvals
5. Join gateway to merge approval paths 