Skip to main content

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ámetroTipoRequeridoDescripciónDefault
tenant_idintegerID del tenant-
segmentstringFiltrar por segmento específiconull
limitintegerNúmero de resultados100
offsetintegerOffset para paginación0
include_detailsbooleanIncluir lista de customersfalse

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

SegmentoRFM ScoresCaracterísticasAcciones Recomendadas
Champions555, 554, 544, 545Compran frecuentemente, gastan mucho, recientesRecompensas VIP, acceso anticipado
Loyal Customers543, 444, 435, 355Buenos compradores, responden a promocionesProgramas de lealtad, upselling
Potential Loyalists553, 551, 552, 541Clientes recientes con potencialEngagement campaigns, onboarding
Recent Customers512, 511, 422, 421Primera compra recienteWelcome series, educación de producto
Promising525, 524, 523, 522Nuevos con potencial de crecimientoIncentivos para segunda compra
Need Attention535, 534, 443, 434Por encima del promedio pero decayendoRe-engagement, ofertas especiales
About to Sleep331, 321, 312, 221Por debajo del promedioReactivación urgente
At Risk255, 254, 245, 244Solían comprar mucho, ahora noWin-back campaigns
Cannot Lose Them155, 154, 144, 214Grandes compradores inactivosContacto personal, grandes descuentos
Hibernating332, 322, 231, 241Muy inactivosCampañas de reactivación
Lost111Sin actividad significativaConsiderar 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ámetroTipoRequeridoDescripciónDefault
tenant_idintegerID del tenant-
tierstringhigh, medium, lownull
min_valuenumberValor mínimo de CLVnull
max_valuenumberValor máximo de CLVnull
sort_bystringclv, orders, recencyclv
sort_orderstringasc, descdesc

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ámetroTipoRequeridoDescripciónDefault
tenant_idintegerID del tenant-
risk_levelstringactive, at_risk, churning, churnednull
days_inactiveintegerDías sin actividadnull
include_predictionsbooleanIncluir probabilidades MLfalse

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ámetroTipoRequeridoDescripciónDefault
tenant_idintegerID del tenant-
periodstringdaily, weekly, monthlymonthly
start_datedateFecha inicio-12 months
end_datedateFecha fintoday

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ámetroTipoRequeridoDescripción
tenant_idintegerID del tenant
periodstringtoday, 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 incluir
  • exclude_segments[]: Array de segmentos a excluir
  • min_value: Valor mínimo de transacción
  • max_value: Valor máximo de transacción

Filtros de Cliente

  • customer_ids[]: Lista específica de IDs
  • email_domain: Dominio de email
  • registration_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

  1. Usar paginación para grandes conjuntos de datos
  2. Cachear respuestas de overview (TTL: 5 min)
  3. Filtrar por período para mejorar performance
  4. Usar include_details=false por defecto
  5. Implementar retry logic para errores 429