> ## Documentation Index
> Fetch the complete documentation index at: https://docs.steerai.autos/llms.txt
> Use this file to discover all available pages before exploring further.

# API de KPI Dashboard

> Gestiona y obtiene KPIs para operaciones del concesionario

## Resumen

La API de KPI Dashboard ofrece metricas y visualizaciones para operaciones automotrices. Monitorea ventas, inventario, satisfaccion del cliente y crea KPIs personalizados para tu negocio.

## Endpoints

### Obtener todos los KPIs

<ParamField path="GET" type="endpoint">
  /kpis
</ParamField>

Obtiene todos los KPIs configurados para el usuario autenticado, incluyendo KPIs integrados y personalizados.

**Response:**

```json theme={null}
[
  {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "key": "avg_days_to_sell",
    "title": "Average Days to Sell",
    "description": "Average number of days from listing to sale",
    "kpiType": "BUILTIN",
    "dataType": "DURATION",
    "value": 28.5,
    "trend": "down",
    "trendPercentage": -12.3,
    "icon": "calendar-days",
    "color": "#282F75",
    "displayOrder": 1,
    "isVisible": true,
    "chartType": "LINE",
    "chartEnabled": true,
    "chartConfig": {
      "timeRange": "30d",
      "showAverage": true
    },
    "createdAt": "2024-01-15T10:30:00Z",
    "updatedAt": "2024-01-15T10:30:00Z"
  }
]
```

***

### Obtener solo KPIs visibles

<ParamField path="GET" type="endpoint">
  /kpis/visible
</ParamField>

Obtiene solo los KPIs marcados como visibles para el dashboard.

**Response:**

Arreglo de KPIs con `isVisible: true`.

***

### Obtener KPI por ID

<ParamField path="GET" type="endpoint">
  /kpis/{id}
</ParamField>

Obtiene informacion detallada de un KPI especifico.

**Path Parameters:**

<ParamField path="id" type="string" required>
  KPI UUID
</ParamField>

**Response:**

```json theme={null}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "key": "gross_profit_margin",
  "title": "Gross Profit Margin",
  "description": "Percentage of revenue remaining after cost of goods sold",
  "formula": "(Revenue - COGS) / Revenue * 100",
  "kpiType": "BUILTIN",
  "dataType": "PERCENTAGE",
  "value": 18.5,
  "trend": "up",
  "trendPercentage": 5.2,
  "icon": "chart-line",
  "color": "#4360B1",
  "displayOrder": 3,
  "isVisible": true,
  "chartType": "AREA",
  "chartEnabled": true,
  "chartConfig": {
    "timeRange": "90d",
    "showAverage": true,
    "showTrendline": true
  }
}
```

***

### Crear KPI personalizado

<ParamField path="POST" type="endpoint">
  /kpis
</ParamField>

Crea un KPI personalizado con tu propia logica de calculo.

**Request Body:**

```json theme={null}
{
  "key": "customer_referral_rate",
  "title": "Customer Referral Rate",
  "description": "Percentage of customers who refer others",
  "formula": "Referrals / Total Customers * 100",
  "kpiType": "CUSTOM",
  "dataType": "PERCENTAGE",
  "icon": "users",
  "color": "#28a745",
  "displayOrder": 10,
  "isVisible": true,
  "aggregation": "average",
  "targetModel": "Customer",
  "targetField": "referralCount"
}
```

<ParamField body="key" type="string" required>
  Identificador unico (minusculas, underscores)
</ParamField>

<ParamField body="title" type="string" required>
  Titulo visible del KPI
</ParamField>

<ParamField body="description" type="string">
  Descripcion de lo que mide el KPI
</ParamField>

<ParamField body="formula" type="string">
  Formula o logica de calculo
</ParamField>

<ParamField body="kpiType" type="enum" required>
  Tipo: `BUILTIN`, `CUSTOM`
</ParamField>

<ParamField body="dataType" type="enum" required>
  Tipo de dato: `NUMBER`, `CURRENCY`, `PERCENTAGE`, `DURATION`, `TEXT`
</ParamField>

<ParamField body="icon" type="string">
  Identificador de icono (FontAwesome)
</ParamField>

<ParamField body="color" type="string">
  Color hex para visualizacion
</ParamField>

<ParamField body="displayOrder" type="number">
  Orden en el dashboard
</ParamField>

<ParamField body="isVisible" type="boolean">
  KPI visible en dashboard (default: true)
</ParamField>

<ParamField body="aggregation" type="string">
  Metodo de agregacion: `sum`, `average`, `count`, `min`, `max`
</ParamField>

<ParamField body="targetModel" type="string">
  Modelo de base de datos a agregar
</ParamField>

<ParamField body="targetField" type="string">
  Campo a agregar
</ParamField>

**Response:**

```json theme={null}
{
  "id": "new_kpi_uuid",
  "key": "customer_referral_rate",
  "title": "Customer Referral Rate",
  "kpiType": "CUSTOM",
  "createdAt": "2024-01-17T09:15:00Z"
}
```

***

### Actualizar KPI

<ParamField path="PATCH" type="endpoint">
  /kpis/{id}
</ParamField>

Actualiza la configuracion de un KPI existente. Los KPIs integrados solo pueden cambiar ajustes de visualizacion, no la logica.

**Path Parameters:**

<ParamField path="id" type="string" required>
  KPI UUID
</ParamField>

**Request Body:**

```json theme={null}
{
  "title": "Updated Title",
  "isVisible": false,
  "displayOrder": 5,
  "color": "#ff6b6b"
}
```

Todos los campos son opcionales. Solo se actualizan los proporcionados.

***

### Eliminar KPI

<ParamField path="DELETE" type="endpoint">
  /kpis/{id}
</ParamField>

Elimina un KPI personalizado. Los KPIs integrados no se pueden eliminar.

**Path Parameters:**

<ParamField path="id" type="string" required>
  KPI UUID
</ParamField>

**Response:**

```json theme={null}
{
  "success": true,
  "message": "Custom KPI deleted successfully"
}
```

<Warning>
  Solo los KPIs personalizados pueden eliminarse. Intentar eliminar un KPI integrado devuelve 400.
</Warning>

***

### Reordenar KPIs

<ParamField path="PUT" type="endpoint">
  /kpis/reorder
</ParamField>

Actualiza el orden de visualizacion de multiples KPIs a la vez.

**Request Body:**

```json theme={null}
{
  "orders": [
    { "id": "kpi_uuid_1", "displayOrder": 1 },
    { "id": "kpi_uuid_2", "displayOrder": 2 },
    { "id": "kpi_uuid_3", "displayOrder": 3 }
  ]
}
```

**Response:**

```json theme={null}
{
  "success": true,
  "message": "KPIs reordered successfully"
}
```

***

### Alternar visibilidad de KPI

<ParamField path="PATCH" type="endpoint">
  /kpis/{id}/toggle
</ParamField>

Activa/desactiva la visibilidad del KPI en el dashboard.

**Path Parameters:**

<ParamField path="id" type="string" required>
  KPI UUID
</ParamField>

**Response:**

```json theme={null}
{
  "id": "550e8400-e29b-41d4-a716-446655440000",
  "isVisible": false,
  "message": "KPI visibility toggled"
}
```

***

### Restablecer KPIs por defecto

<ParamField path="POST" type="endpoint">
  /kpis/reset
</ParamField>

Restablece todos los KPIs a la configuracion por defecto. Esto:

* Restaura KPIs integrados a defaults
* Elimina KPIs personalizados
* Restablece orden y visibilidad

**Response:**

```json theme={null}
{
  "success": true,
  "message": "KPIs reset to defaults successfully",
  "kpisCount": 8
}
```

<Warning>
  Esta accion no se puede deshacer. Todos los KPIs personalizados se perderan.
</Warning>

***

### Actualizar configuracion de grafico KPI

<ParamField path="PATCH" type="endpoint">
  /kpis/{id}/chart
</ParamField>

Configura la visualizacion de grafico para un KPI.

**Path Parameters:**

<ParamField path="id" type="string" required>
  KPI UUID
</ParamField>

**Request Body:**

```json theme={null}
{
  "chartType": "BAR",
  "chartEnabled": true,
  "chartConfig": {
    "timeRange": "30d",
    "showAverage": true,
    "showTrendline": false,
    "colors": ["#282F75", "#4360B1"]
  }
}
```

<ParamField body="chartType" type="enum">
  Tipo: `NONE`, `DONUT`, `BAR`, `LINE`, `AREA`, `RADIAL`
</ParamField>

<ParamField body="chartEnabled" type="boolean">
  Activar/desactivar grafico
</ParamField>

<ParamField body="chartConfig" type="object">
  Opciones de configuracion del grafico
</ParamField>

***

### Obtener datos de grafico KPI

<ParamField path="GET" type="endpoint">
  /kpis/{id}/chart-data
</ParamField>

Obtiene datos historicos para visualizar el grafico del KPI.

**Path Parameters:**

<ParamField path="id" type="string" required>
  KPI UUID
</ParamField>

**Query Parameters:**

<ParamField query="timeRange" type="enum">
  Rango: `7d`, `30d`, `90d` (default: 30d)
</ParamField>

**Response:**

```json theme={null}
{
  "kpiId": "550e8400-e29b-41d4-a716-446655440000",
  "timeRange": "30d",
  "dataPoints": [
    {
      "date": "2024-01-01",
      "value": 25.5,
      "label": "Jan 1"
    },
    {
      "date": "2024-01-02",
      "value": 27.2,
      "label": "Jan 2"
    }
  ],
  "statistics": {
    "min": 22.1,
    "max": 32.8,
    "average": 27.3,
    "trend": "up"
  }
}
```

***

## KPIs integrados

Steer AI incluye los siguientes KPIs por defecto:

| Key                           | Title                    | Data Type  | Description                        |
| ----------------------------- | ------------------------ | ---------- | ---------------------------------- |
| `avg_days_to_sell`            | Average Days to Sell     | DURATION   | Tiempo de listado a venta          |
| `avg_selling_price`           | Average Selling Price    | CURRENCY   | Precio promedio de venta           |
| `gross_profit_margin`         | Gross Profit Margin      | PERCENTAGE | Porcentaje de ingresos menos COGS  |
| `avg_age_of_inventory`        | Average Age of Inventory | DURATION   | Dias en inventario                 |
| `inventory_turnover_ratio`    | Inventory Turnover Ratio | NUMBER     | Velocidad de rotacion              |
| `customer_satisfaction_score` | Customer Satisfaction    | PERCENTAGE | Satisfaccion del cliente           |
| `customer_retention_rate`     | Customer Retention Rate  | PERCENTAGE | Porcentaje de clientes recurrentes |
| `total_repair_cost`           | Total Repair Cost        | CURRENCY   | Suma de costos de reparacion       |

## Tipos de datos

### NUMBER

Valores numericos (ej., 1234, 567.89)

### CURRENCY

Valores monetarios con simbolos (ej., \$1,234.56, MAD 5,000.00)

### PERCENTAGE

Valores en porcentaje (ej., 18.5%, 92.3%)

### DURATION

Periodos de tiempo en dias u horas (ej., 28 dias, 3.5 horas)

### TEXT

Valores de texto para KPIs no numericos

## Tipos de graficos

### DONUT

Grafico circular con distribucion proporcional

### BAR

Barras verticales u horizontales para comparaciones

### LINE

Grafico de lineas para tendencias en el tiempo

### AREA

Grafico de area para tendencias acumuladas

### RADIAL

Grafico radial para metricas de un solo valor

### NONE

Sin visualizacion de grafico

## Casos de uso

### Ejemplo 1: Seguimiento de ventas

```bash theme={null}
# Get visible KPIs for dashboard
curl -X GET "https://api.steerai.autos/v1/kpis/visible" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

### Ejemplo 2: Crear KPI de conversion

```bash theme={null}
curl -X POST "https://api.steerai.autos/v1/kpis" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "key": "lead_conversion_rate",
    "title": "Lead Conversion Rate",
    "description": "Percentage of leads that convert to sales",
    "kpiType": "CUSTOM",
    "dataType": "PERCENTAGE",
    "icon": "chart-line",
    "color": "#28a745"
  }'
```

### Ejemplo 3: Obtener datos historicos

```bash theme={null}
curl -X GET "https://api.steerai.autos/v1/kpis/{kpi_id}/chart-data?timeRange=90d" \
  -H "Authorization: Bearer YOUR_API_KEY"
```

## Mejores practicas

<AccordionGroup>
  <Accordion title="Empieza con KPIs integrados">
    Usa los KPIs integrados antes de crear personalizados. Estan optimizados.
  </Accordion>

  <Accordion title="Limita KPIs del dashboard a 6-8">
    Demasiados KPIs generan ruido. Enfocate en metricas criticas.
  </Accordion>

  <Accordion title="Usa rangos de tiempo consistentes">
    Compara KPIs con los mismos periodos para insights validos.
  </Accordion>

  <Accordion title="Documenta formulas de KPIs personalizados">
    Documenta como se calculan para que el equipo lo entienda.
  </Accordion>

  <Accordion title="Revisa y ajusta regularmente">
    Los KPIs deben evolucionar con el negocio. Revisa trimestralmente.
  </Accordion>
</AccordionGroup>

## Codigos de error

| Code                          | Status | Description                        |
| ----------------------------- | ------ | ---------------------------------- |
| `KPI_NOT_FOUND`               | 404    | El ID del KPI no existe            |
| `CANNOT_DELETE_BUILTIN`       | 400    | No se puede eliminar KPI integrado |
| `CANNOT_MODIFY_BUILTIN_LOGIC` | 400    | No se puede cambiar la logica      |
| `DUPLICATE_KPI_KEY`           | 400    | La key de KPI ya existe            |
| `INVALID_CHART_TYPE`          | 400    | Tipo de grafico no soportado       |

<Card title="Guia de KPIs" icon="gauge-high" href="/es/guides/dashboard-kpis">
  Aprende mas sobre optimizacion del KPI dashboard
</Card>
