Acciones de Control de Flujo
Controla la logica de ejecucion de tus workflows con condiciones, delays y manejo de variables.
Tipos de Control
CONTROL DE FLUJO
| CONDICIONES | TIEMPO | DATOS |
|---|---|---|
| IF/ELSE | DELAY | SET_VARIABLE |
| SWITCH | WAIT_FOR | TRANSFORM |
| FILTER | SCHEDULE | AGGREGATE |
| LOOP | TIMEOUT | LOOKUP |
| CONTROL | ESTADO | SUBFLOWS |
|---|---|---|
| STOP | CHECKPOINT | CALL_WORKFLOW |
| SKIP | RESUME | PARALLEL |
| RETRY | ROLLBACK | MERGE |
CONDITION (IF/ELSE)
Descripcion
Ejecuta acciones condicionalmente basado en expresiones.
Estructura:
- condition: Expresion a evaluar
- thenActions: Acciones si verdadero
- elseActions: Acciones si falso (opcional)
- elseIfConditions: Condiciones adicionales
Operadores soportados:
- Comparacion: ==, !=, >, <, >=, <=
- Logicos: AND, OR, NOT
- Contenido: contains, startsWith, endsWith
- Existencia: exists, isEmpty, isNotEmpty
- Tipo: isNumber, isString, isArray
Ejemplo de Configuracion
{
"actionType": "CONDITION",
"order": 3,
"configuration": {
"condition": "{{matchScore}} >= 80 AND {{hasRequiredSkills}} == true",
"thenActions": [
{ "actionType": "SEND_EMAIL", "template": "interview_invitation" },
{ "actionType": "CREATE_TASK", "type": "schedule_interview" }
],
"elseIfConditions": [
{
"condition": "{{matchScore}} >= 60",
"actions": [
{ "actionType": "SEND_EMAIL", "template": "under_review" }
]
}
],
"elseActions": [
{ "actionType": "SEND_EMAIL", "template": "rejection" },
{ "actionType": "UPDATE_STATUS", "status": "rejected" }
]
}
}
Interfaz Visual
Condicion
SI: matchScore >= 80 Y: hasRequiredSkills == true
ENTONCES:
- Enviar Email (interview_invitation)
- Crear Tarea (schedule_interview)
SINO SI: matchScore >= 60
- Enviar Email (under_review)
SINO:
- Enviar Email (rejection)
- Actualizar Status (rejected)
Expresiones Comunes
Comparacion de numeros:
- {{score}} > 80
- {{experience.years}} >= 3
- {{salary.expected}} <= {{salary.budget}}
Comparacion de texto:
- {{status}} == "pending"
- {{email}} contains "@empresa.com"
- {{name}} startsWith "Dr."
Verificacion de existencia:
- {{phone}} exists
- {{cv}} isNotEmpty
- {{skills}} isEmpty
Arrays:
- {{tags}} includes "urgente"
- {{skills}} length > 5
- {{skills}} any ["React", "Vue"]
Fechas:
- {{dueDate}} < now()
- {{createdAt}} > now() - 7 days
- {{event.date}} between (now(), now() + 30 days)
Combinadas:
- ({{score}} > 70 OR {{referral}} == true) AND {{status}} == "active"
SWITCH
Descripcion
Ejecuta diferentes acciones basado en valor de una variable.
Similar a switch/case en programacion. Mas limpio que multiples IF/ELSE cuando hay muchas opciones.
Ejemplo de Configuracion
{
"actionType": "SWITCH",
"order": 2,
"configuration": {
"value": "{{application.source}}",
"cases": {
"career-page": {
"actions": [
{ "actionType": "ADD_TAG", "tag": "organic" }
]
},
"linkedin": {
"actions": [
{ "actionType": "ADD_TAG", "tag": "linkedin" },
{ "actionType": "SET_VARIABLE", "key": "premium", "value": true }
]
},
"referral": {
"actions": [
{ "actionType": "ADD_TAG", "tag": "referral" },
{ "actionType": "SET_VARIABLE", "key": "priority", "value": "high" }
]
}
},
"default": {
"actions": [
{ "actionType": "ADD_TAG", "tag": "other" }
]
}
}
}
DELAY
Descripcion
Pausa la ejecucion por un tiempo determinado.
Modos:
- Fixed: Tiempo fijo (X minutos/horas/dias)
- Until: Hasta fecha/hora especifica
- BusinessHours: Solo cuenta horas laborales
- Dynamic: Tiempo basado en variable
Ejemplo de Configuracion
Delay fijo:
{
"actionType": "DELAY",
"order": 2,
"configuration": {
"type": "fixed",
"duration": 2,
"unit": "hours"
}
}
Delay hasta fecha:
{
"actionType": "DELAY",
"order": 2,
"configuration": {
"type": "until",
"datetime": "{{event.startTime}} - 1 hour"
}
}
Delay en horas laborales:
{
"actionType": "DELAY",
"order": 2,
"configuration": {
"type": "business_hours",
"duration": 4,
"unit": "hours",
"timezone": "America/Mexico_City",
"businessHours": {
"start": "09:00",
"end": "18:00",
"days": ["mon", "tue", "wed", "thu", "fri"]
}
}
}
Interfaz de Configuracion
Configurar: Delay
| Campo | Valor |
|---|---|
| Tipo de delay | (*) Tiempo fijo / ( ) Hasta fecha/hora / ( ) Horas laborales |
| Duracion | 2 horas |
Opciones:
- Solo dias laborales
- Respetar zona horaria del candidato
WAIT_FOR
Descripcion
Espera hasta que ocurra un evento especifico.
Eventos esperables:
- Otro trigger del mismo workflow
- Actualizacion de campo
- Respuesta del usuario
- Resultado de accion externa
- Timeout
Importante: El workflow queda "pausado" hasta que el evento ocurra
Ejemplo de Configuracion
{
"actionType": "WAIT_FOR",
"order": 3,
"configuration": {
"event": "DOCUMENT_REQUEST_COMPLETED",
"filter": {
"requestId": "{{documentRequest.id}}"
},
"timeout": {
"duration": 7,
"unit": "days",
"onTimeout": "continue" // o "stop" o "branch"
},
"onTimeoutActions": [
{ "actionType": "SEND_EMAIL", "template": "document_reminder" }
]
}
}
Casos de Uso
- Esperar firma: WAIT_FOR SIGNATURE_REQUEST_COMPLETED
- Esperar respuesta: WAIT_FOR MESSAGE_RECEIVED
- Esperar documento: WAIT_FOR DOCUMENT_REQUEST_COMPLETED
- Esperar test: WAIT_FOR TEST_COMPLETED
SET_VARIABLE
Descripcion
Establece o modifica variables para uso posterior.
Las variables:
- Persisten durante la ejecucion
- Pueden usarse en acciones siguientes
- Pueden ser calculadas
- Pueden guardarse en contexto
Tipos de valores:
- Estatico: valor fijo
- Referencia: {{otra.variable}}
- Calculado: expresion
- Resultado: de accion anterior
Ejemplo de Configuracion
{
"actionType": "SET_VARIABLE",
"order": 1,
"configuration": {
"variables": [
{
"name": "candidateFullName",
"value": "{{postulant.firstName}} {{postulant.lastName}}"
},
{
"name": "isUrgent",
"value": "{{job.priority}} == 'high' OR {{daysOpen}} > 30",
"type": "expression"
},
{
"name": "deadline",
"value": "{{now}} + 7 days",
"type": "date"
},
{
"name": "interviewScore",
"value": "{{previousAction.result.score}}",
"type": "reference"
}
]
}
}
Variables Especiales
| Variable | Descripcion |
|---|---|
| {{now}} | Fecha/hora actual |
| {{today}} | Fecha de hoy |
| {{workflow.id}} | ID del workflow |
| {{execution.id}} | ID de ejecucion |
| {{trigger.type}} | Tipo de trigger |
| {{previousAction.result}} | Resultado anterior |
| {{context.*}} | Contexto acumulado |
TRANSFORM
Descripcion
Transforma datos de un formato a otro.
Transformaciones:
- Array -> Object
- Object -> Array
- String -> Number
- Parse JSON
- Format date
- Map/Filter arrays
- Custom expressions
Ejemplo de Configuracion
{
"actionType": "TRANSFORM",
"order": 2,
"configuration": {
"input": "{{candidates}}",
"transformations": [
{
"operation": "filter",
"condition": "item.score >= 70"
},
{
"operation": "map",
"expression": "{ name: item.name, email: item.email, score: item.score }"
},
{
"operation": "sort",
"by": "score",
"order": "desc"
},
{
"operation": "limit",
"count": 5
}
],
"output": "topCandidates"
}
}
LOOP
Descripcion
Ejecuta acciones para cada elemento de una lista.
Configuracion:
- items: Lista a iterar
- itemVariable: Nombre de variable por item
- actions: Acciones a ejecutar
- parallel: Si ejecutar en paralelo
- maxIterations: Limite de iteraciones
Ejemplo de Configuracion
{
"actionType": "LOOP",
"order": 3,
"configuration": {
"items": "{{pendingCandidates}}",
"itemVariable": "candidate",
"parallel": false,
"maxIterations": 100,
"actions": [
{
"actionType": "SEND_EMAIL",
"configuration": {
"to": "{{candidate.email}}",
"template": "reminder"
}
}
]
}
}
Interfaz Visual
LOOP: Para cada candidato
| Campo | Valor |
|---|---|
| Items | {{pendingCandidates}} |
| Variable | candidate |
Acciones por iteracion:
- Enviar Email
- Para: {{candidate.email}}
- Template: reminder
Opciones:
- Ejecutar en paralelo
- Max iteraciones: 100
STOP
Descripcion
Detiene la ejecucion del workflow.
Opciones:
- Detener inmediatamente
- Con mensaje de razon
- Marcar como exitoso o fallido
- Continuar otros workflows
Ejemplo de Configuracion
{
"actionType": "STOP",
"order": 5,
"configuration": {
"reason": "Candidato no cumple requisitos minimos",
"status": "completed", // completed, failed, cancelled
"logDetails": true
}
}
CALL_WORKFLOW
Descripcion
Llama a otro workflow como subrutina.
Usos:
- Reutilizar logica comun
- Modularizar workflows complejos
- Mantener workflows simples
- Compartir funcionalidad
El workflow llamado:
- Recibe parametros
- Ejecuta sus acciones
- Retorna resultado
- No tiene acceso al contexto padre (a menos que se pase)
Ejemplo de Configuracion
{
"actionType": "CALL_WORKFLOW",
"order": 4,
"configuration": {
"workflowId": "send-welcome-package",
"parameters": {
"candidateId": "{{postulant.id}}",
"jobId": "{{job.id}}",
"startDate": "{{offer.startDate}}"
},
"waitForCompletion": true,
"timeout": 300, // segundos
"onComplete": {
"storeResult": "welcomeResult"
}
}
}
PARALLEL
Descripcion
Ejecuta multiples acciones en paralelo.
Beneficios:
- Reduce tiempo total de ejecucion
- Acciones independientes simultaneas
- Merge de resultados al final
- Fallo parcial manejable
Ejemplo de Configuracion
{
"actionType": "PARALLEL",
"order": 2,
"configuration": {
"branches": [
{
"name": "notifications",
"actions": [
{ "actionType": "SEND_EMAIL", "to": "{{postulant.email}}" },
{ "actionType": "SEND_NOTIFICATION", "to": "{{hiringManager}}" }
]
},
{
"name": "analysis",
"actions": [
{ "actionType": "ANALYZE_CV" },
{ "actionType": "CALCULATE_MATCH_SCORE" }
]
},
{
"name": "tasks",
"actions": [
{ "actionType": "CREATE_TASK", "type": "review" }
]
}
],
"waitForAll": true, // o "any" para continuar cuando alguno termine
"onPartialFailure": "continue" // o "stop"
}
}
Interfaz Visual
PARALLEL se divide en ramas:
- Notificar - Email + Notification
- Analizar - CV + Match Score
- Crear Tarea - Task
Todas convergen en MERGE al final.
ERROR_HANDLER
Descripcion
Define manejo de errores para el workflow.
Estrategias:
- Retry: Reintentar N veces
- Skip: Omitir y continuar
- Stop: Detener ejecucion
- Fallback: Ejecutar acciones alternativas
- Notify: Alertar y decidir
Ejemplo de Configuracion
{
"actionType": "ERROR_HANDLER",
"order": 0, // Generalmente al inicio
"configuration": {
"globalHandler": {
"strategy": "retry",
"maxRetries": 3,
"retryDelay": 60, // segundos
"onMaxRetries": "notify"
},
"actionSpecific": {
"SEND_EMAIL": {
"strategy": "fallback",
"fallbackActions": [
{ "actionType": "SEND_SMS", "message": "Por favor revisa tu email" }
]
},
"EXTERNAL_API": {
"strategy": "skip",
"logError": true
}
},
"notifyOn": {
"email": "admin@empresa.com",
"conditions": ["maxRetries", "criticalError"]
}
}
}
Buenas Practicas
Diseno de Flujos
DO:
- Usar nombres descriptivos para variables
- Documentar condiciones complejas
- Manejar todos los casos (else)
- Limitar profundidad de anidacion
- Usar subworkflows para logica repetida
DON'T:
- Condiciones muy complejas en una sola linea
- Loops sin limite de iteraciones
- Ignorar errores
- Delays muy largos sin necesidad
- Variables con nombres genericos
Performance
Recomendaciones:
- Usar PARALLEL cuando sea posible
- Evitar loops grandes
- Timeouts razonables
- Cache de datos repetidos
- Monitorear duracion de ejecuciones
Proximos Pasos
- Acciones de Tareas - Mover candidatos
- Variables y Placeholders - Datos dinamicos
- Ejecucion y Monitoreo - Debugging