Operaciones de Bloques en Notebooks

Crea y administra bloques de análisis dentro de notebooks. Los bloques son los elementos básicos de los flujos de trabajo de análisis.


Tipos de Bloques

Tipo Descripción
Filter Filtrar datos a casos o eventos específicos
Calculator Calcular métricas, duraciones y valores derivados
Opportunity Identificar oportunidades de mejora
Insight Generar visualizaciones y estadísticas
Dashboard Crear paneles de informes para compartir
Alert Definir alertas de monitoreo

Listar Bloques

GET /api/{tenantId}/{projectId}/notebook/{notebookId}/blocks

Devuelve todos los bloques en un notebook en orden de ejecución.

Parámetros de Ruta

Parámetro Tipo Requerido Descripción
tenantId GUID El identificador del tenant
projectId GUID El identificador del proyecto
notebookId GUID El identificador del notebook

Respuesta (200 OK)

{
  "notebookId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  "blocks": [
    {
      "blockId": "11111111-1111-1111-1111-111111111111",
      "blockType": "Filter",
      "operatorName": "ActivityFilter",
      "name": "Select Key Activities",
      "description": "Filter to main process activities",
      "parentId": null,
      "order": 0,
      "configuration": "{\"activities\": [\"Create Order\", \"Approve\", \"Ship\"]}",
      "dateCreated": "2024-01-15T10:30:00Z",
      "createdBy": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "dateModified": "2024-01-15T10:30:00Z",
      "isActive": true
    },
    {
      "blockId": "22222222-2222-2222-2222-222222222222",
      "blockType": "Calculator",
      "operatorName": "DurationCalculator",
      "name": "Case Duration",
      "description": "Calculate total case duration",
      "parentId": "11111111-1111-1111-1111-111111111111",
      "order": 0,
      "configuration": "{\"unit\": \"days\"}",
      "dateCreated": "2024-01-15T10:35:00Z",
      "createdBy": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
      "dateModified": "2024-01-15T10:35:00Z",
      "isActive": true
    }
  ],
  "totalCount": 2
}

Campos del Bloque

Campo Tipo Descripción
blockId GUID Identificador único del bloque
blockType string Tipo (Filter, Calculator, etc.)
operatorName string Nombre específico del operador
name string Nombre para mostrar del bloque
description string Descripción del bloque
parentId GUID ID del bloque padre (flujo de datos desde el padre)
order integer Indicación del orden de ejecución
configuration string Configuración JSON para el operador
dateCreated datetime Fecha y hora de creación
createdBy GUID ID del usuario creador
dateModified datetime Fecha y hora de la última modificación
isActive boolean Si el bloque está habilitado

Crear Bloque

POST /api/{tenantId}/{projectId}/notebook/{notebookId}/blocks

Crea un nuevo bloque de análisis en el notebook.

Parámetros de Ruta

Parámetro Tipo Requerido Descripción
tenantId GUID El identificador del tenant
projectId GUID El identificador del proyecto
notebookId GUID El identificador del notebook

Cuerpo de la Solicitud

{
  "blockType": "Filter",
  "operatorName": "ActivityFilter",
  "name": "Filter by Status",
  "description": "Keep only completed orders",
  "configuration": "{\"activities\": [\"Complete\", \"Shipped\"]}",
  "insertAfterBlockId": "11111111-1111-1111-1111-111111111111"
}

Campos de la Solicitud

Campo Tipo Requerido Descripción
blockType string No Tipo (Filter, Calculator, etc.). Por defecto: Filter
operatorName string Operador específico a usar
name string Nombre para mostrar del bloque
description string No Descripción del bloque
configuration string No Configuración JSON para el operador
insertAfterBlockId GUID No Insertar después de este bloque (por defecto al final)

Respuesta (201 Created)

{
  "blockId": "33333333-3333-3333-3333-333333333333",
  "blockType": "Filter",
  "operatorName": "ActivityFilter",
  "name": "Filter by Status",
  "description": "Keep only completed orders",
  "parentId": "11111111-1111-1111-1111-111111111111",
  "order": 0,
  "configuration": "{\"activities\": [\"Complete\", \"Shipped\"]}",
  "dateCreated": "2024-03-01T10:00:00Z",
  "createdBy": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
  "dateModified": "2024-03-01T10:00:00Z",
  "isActive": true
}

Obtener Orden de Bloques

GET /api/{tenantId}/{projectId}/notebook/{notebookId}/blocks/order

Devuelve el orden actual de ejecución de los bloques.

Respuesta (200 OK)

{
  "notebookId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
  "blockCount": 3,
  "blockOrder": [
    {
      "blockId": "11111111-1111-1111-1111-111111111111",
      "parentId": null,
      "position": 1
    },
    {
      "blockId": "22222222-2222-2222-2222-222222222222",
      "parentId": "11111111-1111-1111-1111-111111111111",
      "position": 2
    },
    {
      "blockId": "33333333-3333-3333-3333-333333333333",
      "parentId": "22222222-2222-2222-2222-222222222222",
      "position": 3
    }
  ]
}

Reordenar Bloques

PUT /api/{tenantId}/{projectId}/notebook/{notebookId}/blocks/order

Cambia el orden de ejecución de los bloques en el notebook.

Cuerpo de la Solicitud

{
  "blockIds": [
    "11111111-1111-1111-1111-111111111111",
    "33333333-3333-3333-3333-333333333333",
    "22222222-2222-2222-2222-222222222222"
  ]
}

Campos de la Solicitud

Campo Tipo Requerido Descripción
blockIds array IDs de bloques en el orden deseado de ejecución

Respuesta (200 OK)

Devuelve el orden de bloques actualizado.


Flujo de Ejecución de Bloques

Los bloques forman una cadena donde cada bloque recibe datos de su bloque padre:

[Inicio de Investigación]
       |
       v
[Filtro: Activity Filter] -> Filtra a actividades específicas
       |
       v
[Calculadora: Duración] -> Calcula duraciones para datos filtrados
       |
       v
[Insight: Estadísticas] -> Genera estadísticas sobre datos calculados

Al reordenar bloques, la cadena padre se actualiza automáticamente.


Ejemplos de Implementación

Python

import requests
import json

BASE_URL = 'https://your-mindzie-instance.com'
TENANT_ID = '12345678-1234-1234-1234-123456789012'
PROJECT_ID = '87654321-4321-4321-4321-210987654321'

class BlockManager:
    def __init__(self, api_key):
        self.headers = {
            'Authorization': f'Bearer {api_key}',
            'Content-Type': 'application/json'
        }

    def list_blocks(self, notebook_id):
        """Lista todos los bloques en un notebook."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/notebook/{notebook_id}/blocks'
        response = requests.get(url, headers=self.headers)
        response.raise_for_status()
        return response.json()

    def create_block(self, notebook_id, block_type, operator_name, name,
                     description=None, configuration=None, insert_after=None):
        """Crea un nuevo bloque."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/notebook/{notebook_id}/blocks'
        data = {
            'blockType': block_type,
            'operatorName': operator_name,
            'name': name,
            'description': description,
            'configuration': json.dumps(configuration) if configuration else None,
            'insertAfterBlockId': insert_after
        }
        response = requests.post(url, json=data, headers=self.headers)
        response.raise_for_status()
        return response.json()

    def get_block_order(self, notebook_id):
        """Obtiene el orden actual de ejecución de bloques."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/notebook/{notebook_id}/blocks/order'
        response = requests.get(url, headers=self.headers)
        response.raise_for_status()
        return response.json()

    def reorder_blocks(self, notebook_id, block_ids):
        """Reordena los bloques en el notebook."""
        url = f'{BASE_URL}/api/{TENANT_ID}/{PROJECT_ID}/notebook/{notebook_id}/blocks/order'
        response = requests.put(url, json={'blockIds': block_ids}, headers=self.headers)
        response.raise_for_status()
        return response.json()

# Uso
manager = BlockManager('your-api-key')
notebook_id = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'

# Listar bloques
blocks = manager.list_blocks(notebook_id)
print(f"Encontrados {blocks['totalCount']} bloques")

# Crear un bloque filtro
filter_block = manager.create_block(
    notebook_id,
    block_type='Filter',
    operator_name='ActivityFilter',
    name='Select Key Activities',
    configuration={'activities': ['Create Order', 'Approve', 'Ship']}
)
print(f"Filtro creado: {filter_block['blockId']}")

# Crear un bloque calculadora después del filtro
calc_block = manager.create_block(
    notebook_id,
    block_type='Calculator',
    operator_name='DurationCalculator',
    name='Case Duration',
    configuration={'unit': 'days'},
    insert_after=filter_block['blockId']
)
print(f"Calculadora creada: {calc_block['blockId']}")

# Verificar orden de ejecución
order = manager.get_block_order(notebook_id)
print(f"Orden de bloques: {[b['blockId'] for b in order['blockOrder']]}")

JavaScript/Node.js

const BASE_URL = 'https://your-mindzie-instance.com';
const TENANT_ID = '12345678-1234-1234-1234-123456789012';
const PROJECT_ID = '87654321-4321-4321-4321-210987654321';

class BlockManager {
  constructor(apiKey) {
    this.headers = {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    };
  }

  async listBlocks(notebookId) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/notebook/${notebookId}/blocks`;
    const response = await fetch(url, { headers: this.headers });
    if (!response.ok) throw new Error(`Falló: ${response.status}`);
    return response.json();
  }

  async createBlock(notebookId, blockType, operatorName, name, options = {}) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/notebook/${notebookId}/blocks`;
    const body = {
      blockType,
      operatorName,
      name,
      description: options.description,
      configuration: options.configuration ? JSON.stringify(options.configuration) : null,
      insertAfterBlockId: options.insertAfter
    };
    const response = await fetch(url, {
      method: 'POST',
      headers: this.headers,
      body: JSON.stringify(body)
    });
    if (!response.ok) throw new Error(`Falló: ${response.status}`);
    return response.json();
  }

  async reorderBlocks(notebookId, blockIds) {
    const url = `${BASE_URL}/api/${TENANT_ID}/${PROJECT_ID}/notebook/${notebookId}/blocks/order`;
    const response = await fetch(url, {
      method: 'PUT',
      headers: this.headers,
      body: JSON.stringify({ blockIds })
    });
    if (!response.ok) throw new Error(`Falló: ${response.status}`);
    return response.json();
  }
}

// Uso
const manager = new BlockManager('your-api-key');
const notebookId = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee';

// Listar bloques
const blocks = await manager.listBlocks(notebookId);
console.log(`Encontrados ${blocks.totalCount} bloques`);

// Crear bloques
const filter = await manager.createBlock(notebookId, 'Filter', 'ActivityFilter', 'Key Activities', {
  configuration: { activities: ['Create', 'Approve'] }
});

const calc = await manager.createBlock(notebookId, 'Calculator', 'DurationCalculator', 'Duration', {
  insertAfter: filter.blockId
});

Buenas Prácticas

  1. El Orden de Bloques Importa: Los datos fluyen de padre a hijo - planifica tu flujo de trabajo
  2. Usa Plantillas: Para flujos complejos, crea a partir de plantillas
  3. Configuración JSON: Guarda configuraciones específicas del operador como cadenas JSON
  4. InsertAfter: Usa insertAfterBlockId para controlar el posicionamiento
  5. Ejecución: Después de crear bloques, ejecuta el notebook para ver resultados