erp-core/docs/04-modelado/requerimientos-funcionales/mgn-017/RF-MGN-017-005-chatbot-automatizado.md

10 KiB

RF-MGN-017-005: Chatbot Automatizado (Flujos)

Módulo: MGN-017 - WhatsApp Business Integration Prioridad: P2 Story Points: 13 Estado: Definido Fecha: 2025-12-05

Descripción

El sistema debe permitir crear chatbots automatizados para WhatsApp usando un editor visual de flujos. Los chatbots pueden responder automáticamente a mensajes, recopilar información, y escalar a agentes humanos cuando sea necesario. También pueden integrarse con agentes de IA (MGN-018) para respuestas más inteligentes.

Actores

  • Actor Principal: Tenant Admin (crea/edita flujos)
  • Actores Secundarios:
    • Cliente (interactúa con chatbot)
    • Agente humano (recibe escalaciones)
    • AI Agent (respuestas inteligentes)

Precondiciones

  1. Cuenta de WhatsApp Business conectada (RF-017-001)
  2. Feature whatsapp_chatbot habilitado
  3. Templates necesarios aprobados (si aplica)

Conceptos Clave

Flujo (Flow)

Secuencia de nodos que define la conversación automatizada.

Nodo (Node)

Unidad individual del flujo. Tipos:

  • Message: Envía mensaje al usuario
  • Question: Pregunta con opciones o input libre
  • Condition: Bifurcación basada en condiciones
  • Action: Ejecuta acción (crear lead, asignar agente)
  • API Call: Llama a endpoint externo
  • AI Response: Genera respuesta con IA
  • Transfer: Escala a agente humano

Trigger

Evento que inicia el flujo:

  • Palabra clave ("hola", "cotización")
  • Primera interacción
  • Horario específico
  • Evento del sistema

Flujo Principal - Crear Chatbot

  1. Admin accede a "WhatsApp > Chatbots"
  2. Admin selecciona "Crear nuevo chatbot"
  3. Sistema muestra editor visual de flujos
  4. Admin configura trigger inicial
  5. Admin arrastra y conecta nodos
  6. Admin configura cada nodo (mensajes, condiciones)
  7. Admin guarda borrador
  8. Admin prueba flujo con simulador
  9. Admin activa chatbot
  10. Sistema comienza a procesar conversaciones

Tipos de Nodos

1. Message Node

{
  "type": "message",
  "content": {
    "text": "¡Hola {{nombre}}! Bienvenido a nuestra tienda.",
    "media": null,
    "buttons": [
      { "id": "ver_productos", "text": "Ver productos" },
      { "id": "soporte", "text": "Hablar con agente" }
    ]
  }
}

2. Question Node

{
  "type": "question",
  "content": {
    "text": "¿Cuál es tu correo electrónico?",
    "input_type": "email",
    "variable": "user_email",
    "validation": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
    "error_message": "Por favor ingresa un correo válido"
  }
}

3. Condition Node

{
  "type": "condition",
  "conditions": [
    {
      "variable": "intent",
      "operator": "equals",
      "value": "comprar",
      "next_node": "show_products"
    },
    {
      "variable": "intent",
      "operator": "equals",
      "value": "soporte",
      "next_node": "transfer_agent"
    }
  ],
  "default_node": "menu_principal"
}

4. Action Node

{
  "type": "action",
  "action": "create_lead",
  "params": {
    "name": "{{user_name}}",
    "email": "{{user_email}}",
    "phone": "{{wa_number}}",
    "source": "whatsapp_chatbot"
  }
}

5. AI Response Node

{
  "type": "ai_response",
  "config": {
    "agent_id": "uuid-agent",
    "context": "Eres un asistente de ventas de {{company_name}}",
    "max_tokens": 500,
    "fallback_node": "transfer_agent"
  }
}

6. Transfer Node

{
  "type": "transfer",
  "config": {
    "team": "soporte",
    "message": "Te estamos transfiriendo con un agente...",
    "priority": "high",
    "context_variables": ["user_name", "issue_type"]
  }
}

Reglas de Negocio

  • RN-1: Solo un chatbot activo por número de WhatsApp
  • RN-2: Flujos deben tener nodo de inicio y al menos un fin
  • RN-3: Sesión de chatbot expira después de 24h de inactividad
  • RN-4: Escalación a humano siempre debe ser posible
  • RN-5: Variables se persisten durante toda la sesión
  • RN-6: Máximo 50 nodos por flujo (para rendimiento)
  • RN-7: AI nodes requieren feature whatsapp_ai_agent

Criterios de Aceptación

  • Editor visual drag-and-drop funcional
  • Todos los tipos de nodos implementados
  • Simulador de pruebas disponible
  • Variables de sesión funcionan correctamente
  • Condiciones evalúan correctamente
  • Escalación a agente funciona
  • Integración con AI Agent funciona
  • Métricas de uso disponibles
  • Versionado de flujos (rollback)

Entidades Involucradas

messaging.chatbot_flows

CREATE TABLE messaging.chatbot_flows (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    tenant_id UUID NOT NULL REFERENCES core_tenants.tenants(id),
    account_id UUID NOT NULL REFERENCES messaging.whatsapp_accounts(id),

    name VARCHAR(100) NOT NULL,
    description TEXT,
    status VARCHAR(20) NOT NULL DEFAULT 'draft', -- draft, active, paused

    -- Trigger configuration
    trigger_type VARCHAR(50) NOT NULL, -- keyword, first_message, schedule
    trigger_config JSONB NOT NULL,
    -- {
    --   "keywords": ["hola", "info", "cotización"],
    --   "match_type": "contains" | "exact"
    -- }

    -- Flow definition
    nodes JSONB NOT NULL DEFAULT '[]',
    edges JSONB NOT NULL DEFAULT '[]',
    variables JSONB NOT NULL DEFAULT '{}', -- Variables globales del flujo

    -- Versioning
    version INT NOT NULL DEFAULT 1,
    published_at TIMESTAMPTZ,
    published_by UUID,

    -- Stats
    total_sessions INT DEFAULT 0,
    completed_sessions INT DEFAULT 0,
    avg_duration_seconds INT,

    created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    created_by UUID,

    CONSTRAINT chk_status CHECK (status IN ('draft', 'active', 'paused', 'archived'))
);

CREATE INDEX idx_chatbot_flows_tenant ON messaging.chatbot_flows(tenant_id);
CREATE INDEX idx_chatbot_flows_account ON messaging.chatbot_flows(account_id);

messaging.chatbot_sessions

CREATE TABLE messaging.chatbot_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    flow_id UUID NOT NULL REFERENCES messaging.chatbot_flows(id),
    conversation_id UUID NOT NULL REFERENCES messaging.whatsapp_conversations(id),

    -- Estado
    status VARCHAR(20) NOT NULL DEFAULT 'active',
    current_node_id VARCHAR(100),

    -- Variables de sesión
    variables JSONB NOT NULL DEFAULT '{}',
    -- {
    --   "user_name": "Juan",
    --   "user_email": "juan@email.com",
    --   "selected_product": "SKU-123"
    -- }

    -- Tracking
    nodes_visited TEXT[] DEFAULT '{}',
    started_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    last_activity_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
    completed_at TIMESTAMPTZ,
    transferred_at TIMESTAMPTZ,
    transferred_to UUID, -- Agent ID

    CONSTRAINT chk_session_status CHECK (status IN ('active', 'completed', 'transferred', 'expired'))
);

CREATE INDEX idx_chatbot_sessions_flow ON messaging.chatbot_sessions(flow_id);
CREATE INDEX idx_chatbot_sessions_conversation ON messaging.chatbot_sessions(conversation_id);

Editor Visual

Estructura del Canvas

interface FlowCanvas {
  nodes: FlowNode[];
  edges: FlowEdge[];
  viewport: { x: number; y: number; zoom: number };
}

interface FlowNode {
  id: string;
  type: NodeType;
  position: { x: number; y: number };
  data: NodeData;
}

interface FlowEdge {
  id: string;
  source: string;
  target: string;
  label?: string;
  condition?: string;
}

Librería Recomendada

  • React Flow para el editor visual
  • Persistencia en JSONB de PostgreSQL

Simulador de Pruebas

// POST /api/v1/chatbot/flows/{id}/simulate
interface SimulateRequest {
  initial_message: string;
  mock_variables?: Record<string, any>;
}

interface SimulateResponse {
  session_id: string;
  messages: Array<{
    direction: 'in' | 'out';
    content: string;
    node_id: string;
    timestamp: Date;
  }>;
  current_node: string;
  variables: Record<string, any>;
  is_complete: boolean;
}

Integración con AI Agent (MGN-018)

Cuando un nodo es de tipo ai_response, el sistema:

  1. Obtiene contexto de la conversación
  2. Obtiene variables de sesión
  3. Envía prompt al AI Agent configurado
  4. Recibe respuesta generada
  5. Envía respuesta al usuario
  6. Si AI no puede responder, ejecuta fallback
interface AINodeRequest {
  agent_id: string;
  conversation_context: Message[];
  session_variables: Record<string, any>;
  user_message: string;
}

interface AINodeResponse {
  success: boolean;
  response?: string;
  confidence?: number;
  fallback_triggered?: boolean;
  suggested_next_node?: string;
}

Métricas de Chatbot

interface ChatbotMetrics {
  flow_id: string;
  period: 'day' | 'week' | 'month';

  sessions: {
    total: number;
    completed: number;
    transferred: number;
    expired: number;
  };

  completion_rate: number;
  transfer_rate: number;
  avg_duration_seconds: number;

  node_analytics: Array<{
    node_id: string;
    visits: number;
    exits: number;
    avg_time_seconds: number;
  }>;

  common_paths: Array<{
    path: string[];
    count: number;
  }>;
}

Ejemplos de Flujos

1. Flujo de Bienvenida

[Start] → [Welcome Message] → [Menu Options]
                                    ↓
                    ┌───────────────┼───────────────┐
                    ↓               ↓               ↓
              [Products]      [Support]       [FAQ]
                    ↓               ↓               ↓
              [Show List]    [Transfer]     [AI Response]

2. Flujo de Captura de Lead

[Keyword: cotización] → [Ask Name] → [Ask Email] → [Ask Product]
                                                        ↓
                                               [Create Lead]
                                                        ↓
                                               [Confirm + Transfer]

Referencias

Dependencias

  • RF Requeridos: RF-017-001 (Conexión), RF-017-004 (Inbox)
  • Opcional: MGN-018 (AI Agents) para nodos de IA
  • Bloqueante para: Ninguno