Analytics API Endpoints
Overview
Los endpoints de Analytics proporcionan acceso a los datos procesados del CDP, incluyendo análisis RFM, Customer Lifetime Value y predicción de churn. Estos endpoints son de solo lectura y están optimizados para dashboards y reportes.
🎯 Casos de Uso
- Dashboards ejecutivos: Métricas agregadas y KPIs
- Segmentación de marketing: Identificación de audiencias
- Análisis de retención: Monitoreo de churn y engagement
- Reportes de valor: CLV y rentabilidad por segmento
Endpoints Disponibles
1. RFM Analysis
Análisis de Recencia, Frecuencia y Valor Monetario.
GET /api/v2/cdp/analytics/rfm
Query Parameters
| Parámetro | Tipo | Requerido | Descripción | Default |
|---|---|---|---|---|
tenant_id | integer | ✅ | ID del tenant | - |
segment | string | ❌ | Filtrar por segmento específico | null |
limit | integer | ❌ | Número de resultados | 100 |
offset | integer | ❌ | Offset para paginación | 0 |
include_details | boolean | ❌ | Incluir lista de customers | false |
Response Structure
{
"success": true,
"message": "RFM analysis retrieved successfully",
"data": {
"overview": {
"total_customers": 65226,
"avg_recency": 428.01,
"avg_frequency": 1.5,
"avg_monetary": 2500.50,
"total_revenue": 163065000,
"last_calculation": "2024-09-16T19:16:40.897Z"
},
"distribution": [
{
"segment": "Champions",
"customer_count": 16125,
"percentage": 24.72,
"avg_recency": 30,
"avg_frequency": 5.2,
"avg_monetary": 8500.00,
"characteristics": {
"description": "Best customers, buy frequently and spend the most",
"recommended_actions": [
"Reward with exclusive offers",
"Early access to new products",
"VIP customer service"
]
}
}
],
"trends": {
"champions_growth": "+5.2%",
"at_risk_increase": "+2.1%",
"avg_monetary_change": "+12.5%"
},
"segments_detail": {
"Champions": {
"count": 16125,
"percentage": 24.72,
"customer_ids": [12345, 67890] // Solo si include_details=true
}
}
},
"metadata": {
"tenant_id": 56,
"processing_date": "2024-09-16T19:16:40.897Z",
"next_update": "2024-09-17T01:00:00.000Z"
}
}
Segmentos RFM Detallados
| Segmento | RFM Scores | Características | Acciones Recomendadas |
|---|---|---|---|
| Champions | 555, 554, 544, 545 | Compran frecuentemente, gastan mucho, recientes | Recompensas VIP, acceso anticipado |
| Loyal Customers | 543, 444, 435, 355 | Buenos compradores, responden a promociones | Programas de lealtad, upselling |
| Potential Loyalists | 553, 551, 552, 541 | Clientes recientes con potencial | Engagement campaigns, onboarding |
| Recent Customers | 512, 511, 422, 421 | Primera compra reciente | Welcome series, educación de producto |
| Promising | 525, 524, 523, 522 | Nuevos con potencial de crecimiento | Incentivos para segunda compra |
| Need Attention | 535, 534, 443, 434 | Por encima del promedio pero decayendo | Re-engagement, ofertas especiales |
| About to Sleep | 331, 321, 312, 221 | Por debajo del promedio | Reactivación urgente |
| At Risk | 255, 254, 245, 244 | Solían comprar mucho, ahora no | Win-back campaigns |
| Cannot Lose Them | 155, 154, 144, 214 | Grandes compradores inactivos | Contacto personal, grandes descuentos |
| Hibernating | 332, 322, 231, 241 | Muy inactivos | Campañas de reactivación |
| Lost | 111 | Sin actividad significativa | Considerar eliminar o última oportunidad |
2. Customer Lifetime Value (CLV)
Análisis del valor de vida del cliente.
GET /api/v2/cdp/analytics/clv
Query Parameters
| Parámetro | Tipo | Requerido | Descripción | Default |
|---|---|---|---|---|
tenant_id | integer | ✅ | ID del tenant | - |
tier | string | ❌ | high, medium, low | null |
min_value | number | ❌ | Valor mínimo de CLV | null |
max_value | number | ❌ | Valor máximo de CLV | null |
sort_by | string | ❌ | clv, orders, recency | clv |
sort_order | string | ❌ | asc, desc | desc |
Response
{
"success": true,
"data": {
"overview": {
"total_customers": 45282,
"avg_clv": 15000.50,
"median_clv": 8500.00,
"total_clv": 679230000,
"distribution": {
"high": {
"count": 5000,
"percentage": 11.04,
"avg_value": 75000,
"threshold": "> 50000"
},
"medium": {
"count": 20000,
"percentage": 44.16,
"avg_value": 25000,
"threshold": "10000 - 50000"
},
"low": {
"count": 20282,
"percentage": 44.80,
"avg_value": 5000,
"threshold": "< 10000"
}
}
},
"top_customers": [
{
"customer_id": 12345,
"email": "vip@example.com",
"historical_value": 150000,
"predicted_value": 200000,
"total_clv": 350000,
"total_orders": 45,
"avg_order_value": 3333.33,
"customer_since": "2020-01-15",
"days_as_customer": 1340,
"clv_tier": "high",
"growth_rate": 0.33
}
],
"insights": {
"high_value_concentration": "11% of customers generate 65% of total CLV",
"growth_opportunity": "Medium tier has highest growth potential",
"retention_impact": "1% improvement in retention = $6.7M additional CLV"
}
}
}
3. Churn Analysis
Predicción y análisis de pérdida de clientes.
GET /api/v2/cdp/analytics/churn
Query Parameters
| Parámetro | Tipo | Requerido | Descripción | Default |
|---|---|---|---|---|
tenant_id | integer | ✅ | ID del tenant | - |
risk_level | string | ❌ | active, at_risk, churning, churned | null |
days_inactive | integer | ❌ | Días sin actividad | null |
include_predictions | boolean | ❌ | Incluir probabilidades ML | false |
Response
{
"success": true,
"data": {
"overview": {
"total_customers": 29707,
"churn_rate": 0.15,
"monthly_churn_rate": 0.05,
"at_risk_count": 4456,
"save_rate": 0.25,
"distribution": {
"active": {
"count": 20000,
"percentage": 67.31,
"definition": "< 30 días sin compra"
},
"at_risk": {
"count": 4456,
"percentage": 15.00,
"definition": "30-60 días sin compra"
},
"churning": {
"count": 3000,
"percentage": 10.10,
"definition": "60-90 días sin compra"
},
"churned": {
"count": 2251,
"percentage": 7.58,
"definition": "> 90 días sin compra"
}
}
},
"at_risk_customers": [
{
"customer_id": 67890,
"email": "customer@example.com",
"last_order_date": "2024-06-15",
"days_since_last_order": 93,
"order_frequency_days": 30,
"expected_order_date": "2024-07-15",
"days_overdue": 63,
"churn_probability": 0.75,
"churn_risk": "at_risk",
"recommended_action": "Send win-back offer",
"potential_loss": 5000
}
],
"predictions": {
"next_month_churn": 850,
"preventable_churn": 425,
"potential_save_value": 2125000
},
"trends": {
"churn_rate_trend": "increasing",
"monthly_comparison": "+2.1%",
"seasonal_factor": 1.2
}
}
}
4. Cohort Analysis
Análisis de cohortes por fecha de registro.
GET /api/v2/cdp/analytics/cohorts
Query Parameters
| Parámetro | Tipo | Requerido | Descripción | Default |
|---|---|---|---|---|
tenant_id | integer | ✅ | ID del tenant | - |
period | string | ❌ | daily, weekly, monthly | monthly |
start_date | date | ❌ | Fecha inicio | -12 months |
end_date | date | ❌ | Fecha fin | today |
Response
{
"success": true,
"data": {
"cohorts": [
{
"cohort": "2024-01",
"size": 5000,
"retention": {
"month_0": 100,
"month_1": 85,
"month_2": 72,
"month_3": 65,
"month_6": 45,
"month_12": 35
},
"revenue": {
"total": 2500000,
"per_customer": 500,
"growth": 0.15
}
}
],
"insights": {
"best_cohort": "2024-03",
"worst_cohort": "2023-11",
"avg_retention_3m": 68,
"trend": "improving"
}
}
}
5. Segment Performance
Rendimiento comparativo de segmentos.
GET /api/v2/cdp/analytics/segments/performance
Response
{
"success": true,
"data": {
"segments": [
{
"name": "Champions",
"metrics": {
"size": 16125,
"revenue": 137062500,
"avg_order_value": 8500,
"order_frequency": 5.2,
"retention_rate": 0.95,
"growth_rate": 0.12
},
"comparison": {
"vs_avg_revenue": "+340%",
"vs_avg_retention": "+58%",
"vs_last_month": "+5.2%"
}
}
],
"recommendations": [
{
"segment": "At Risk",
"action": "Immediate intervention needed",
"potential_impact": "$2.5M revenue save"
}
]
}
}
📊 Métricas Agregadas
Dashboard Metrics Endpoint
Endpoint especial para dashboards con todas las métricas clave.
GET /api/v2/cdp/analytics/dashboard
Query Parameters
| Parámetro | Tipo | Requerido | Descripción |
|---|---|---|---|
tenant_id | integer | ✅ | ID del tenant |
period | string | ❌ | today, week, month, year |
Response
{
"success": true,
"data": {
"kpis": {
"total_customers": 65226,
"active_customers": 45000,
"total_revenue": 163065000,
"avg_order_value": 2500,
"customer_lifetime_value": 15000,
"churn_rate": 0.15,
"nps_score": 72
},
"trends": {
"revenue": {
"current": 163065000,
"previous": 150000000,
"change": "+8.7%",
"chart": [/* daily values */]
},
"customers": {
"new": 5000,
"returning": 40000,
"churned": 2251
}
},
"segments": {
"distribution": [/* segment percentages */],
"movements": {
"upgrades": 1200,
"downgrades": 800
}
},
"alerts": [
{
"type": "warning",
"message": "Churn rate increased 2.1% vs last month",
"action": "Review at-risk segment"
}
]
}
}
🔍 Filtros Avanzados
Todos los endpoints de analytics soportan filtros avanzados mediante query parameters:
Filtros Temporales
date_from: Fecha inicio (ISO 8601)date_to: Fecha fin (ISO 8601)period: today, yesterday, week, month, quarter, year
Filtros de Segmentación
segments[]: Array de segmentos a incluirexclude_segments[]: Array de segmentos a excluirmin_value: Valor mínimo de transacciónmax_value: Valor máximo de transacción
Filtros de Cliente
customer_ids[]: Lista específica de IDsemail_domain: Dominio de emailregistration_source: Fuente de registro
📈 Exportación de Datos
Todos los endpoints soportan exportación agregando el parámetro format:
GET /api/v2/cdp/analytics/rfm?tenant_id=56&format=csv
GET /api/v2/cdp/analytics/rfm?tenant_id=56&format=excel
GET /api/v2/cdp/analytics/rfm?tenant_id=56&format=json
🚀 Performance
Tiempos de Respuesta
- Overview endpoints: < 100ms
- Detailed analysis: < 500ms
- Export operations: < 2s
Límites
- Max results per page: 1000
- Max export rows: 50000
- Rate limit: 100 req/min
💡 Best Practices
- Usar paginación para grandes conjuntos de datos
- Cachear respuestas de overview (TTL: 5 min)
- Filtrar por período para mejorar performance
- Usar include_details=false por defecto
- Implementar retry logic para errores 429