Skip to main content
GET
/
events
/
user
/
stats
Estatísticas
curl --request GET \
  --url http://api.gu1.ai/events/user/stats \
  --header 'Authorization: Bearer <token>'
{
  "success": true,
  "stats": [
    {
      "stats[].event_type": "<string>",
      "stats[].count": 123,
      "stats[].last_occurrence": "<string>"
    }
  ]
}

Documentation Index

Fetch the complete documentation index at: https://docs.gu1.ai/llms.txt

Use this file to discover all available pages before exploring further.

Visão Geral

Recupera estatísticas agregadas sobre eventos de usuários, agrupadas por tipo de evento. Este endpoint fornece uma visão rápida da distribuição de eventos, contagens e timestamps da última ocorrência, perfeito para construir dashboards e monitorar padrões de atividade do usuário.

Endpoint

GET https://api.gu1.ai/events/user/stats

Autenticação

Requer uma chave de API válida no cabeçalho Authorization:
Authorization: Bearer YOUR_API_KEY

Parâmetros de Consulta

user_id
string
Filtrar estatísticas por identificador de usuário. Se não fornecido, retorna estatísticas de todos os usuários em sua organização.Exemplo: ?user_id=user_12345

Resposta

success
boolean
Indica se a requisição foi bem-sucedida
stats
array
Array de objetos de estatísticas agrupados por tipo de evento
stats[].event_type
string
O tipo de evento (ex: “LOGIN_SUCCESS”, “TRANSFER_SUCCESS”)
stats[].count
number
Número total de eventos deste tipo
stats[].last_occurrence
string
Timestamp do evento mais recente deste tipo (ISO 8601)

Exemplos

Obter Estatísticas para Todos os Usuários

curl https://api.gu1.ai/events/user/stats \
  -H "Authorization: Bearer YOUR_API_KEY"

Obter Estatísticas para Usuário Específico

curl "https://api.gu1.ai/events/user/stats?user_id=user_12345" \
  -H "Authorization: Bearer YOUR_API_KEY"

Exemplo de Resposta

{
  "success": true,
  "stats": [
    {
      "event_type": "LOGIN_SUCCESS",
      "count": 45,
      "last_occurrence": "2026-01-30T14:30:00Z"
    },
    {
      "event_type": "LOGIN_FAILED",
      "count": 3,
      "last_occurrence": "2026-01-30T08:15:00Z"
    },
    {
      "event_type": "TRANSFER_SUCCESS",
      "count": 12,
      "last_occurrence": "2026-01-30T12:00:00Z"
    },
    {
      "event_type": "PROFILE_UPDATED",
      "count": 2,
      "last_occurrence": "2026-01-25T10:30:00Z"
    },
    {
      "event_type": "PASSWORD_CHANGE",
      "count": 1,
      "last_occurrence": "2026-01-20T16:45:00Z"
    }
  ]
}

Respostas de Erro

401 Unauthorized

{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}

403 Forbidden

{
  "success": false,
  "error": {
    "code": "FORBIDDEN",
    "message": "Insufficient permissions to read events"
  }
}

500 Internal Server Error

{
  "success": false,
  "error": {
    "code": "STATS_FETCH_FAILED",
    "message": "Failed to fetch event statistics"
  }
}

Casos de Uso

Resumo do Dashboard

Construa um dashboard mostrando a distribuição de eventos:
async function buildEventDashboard(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Agrupar por categoria
  const authEvents = data.stats.filter(s =>
    ['LOGIN_SUCCESS', 'LOGIN_FAILED', 'LOGOUT'].includes(s.event_type)
  );

  const transferEvents = data.stats.filter(s =>
    ['TRANSFER_SUCCESS', 'TRANSFER_FAILED'].includes(s.event_type)
  );

  return {
    authentication: {
      total: authEvents.reduce((sum, e) => sum + e.count, 0),
      events: authEvents
    },
    transfers: {
      total: transferEvents.reduce((sum, e) => sum + e.count, 0),
      events: transferEvents
    }
  };
}

Monitoramento de Fraude

Monitore padrões de atividade suspeita:
async function detectSuspiciousActivity(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();
  const alerts = [];

  // Verificar tentativas de login falhas
  const failedLogins = data.stats.find(s => s.event_type === 'LOGIN_FAILED');
  if (failedLogins && failedLogins.count > 5) {
    alerts.push({
      type: 'HIGH_FAILED_LOGINS',
      count: failedLogins.count,
      lastOccurrence: failedLogins.last_occurrence
    });
  }

  // Verificar atividade de transferência
  const transfers = data.stats.find(s => s.event_type === 'TRANSFER_SUCCESS');
  if (transfers && transfers.count > 10) {
    alerts.push({
      type: 'HIGH_TRANSFER_VOLUME',
      count: transfers.count,
      lastOccurrence: transfers.last_occurrence
    });
  }

  return alerts;
}

Relatório de Atividade do Usuário

Gerar relatórios de atividade:
async function generateActivityReport(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  const report = {
    userId,
    generatedAt: new Date().toISOString(),
    totalEvents: data.stats.reduce((sum, s) => sum + s.count, 0),
    eventsByType: data.stats.map(s => ({
      type: s.event_type,
      count: s.count,
      lastActivity: s.last_occurrence
    })),
    mostRecentActivity: data.stats.reduce((latest, s) =>
      new Date(s.last_occurrence) > new Date(latest.last_occurrence)
        ? s
        : latest
    )
  };

  return report;
}

Métricas de Análise

Calcular métricas principais:
async function calculateMetrics(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Calcular taxas de sucesso
  const loginSuccess = data.stats.find(s => s.event_type === 'LOGIN_SUCCESS')?.count || 0;
  const loginFailed = data.stats.find(s => s.event_type === 'LOGIN_FAILED')?.count || 0;
  const loginSuccessRate = loginSuccess / (loginSuccess + loginFailed) * 100;

  const transferSuccess = data.stats.find(s => s.event_type === 'TRANSFER_SUCCESS')?.count || 0;
  const transferFailed = data.stats.find(s => s.event_type === 'TRANSFER_FAILED')?.count || 0;
  const transferSuccessRate = transferSuccess / (transferSuccess + transferFailed) * 100;

  return {
    loginSuccessRate: loginSuccessRate.toFixed(2) + '%',
    transferSuccessRate: transferSuccessRate.toFixed(2) + '%',
    totalLogins: loginSuccess + loginFailed,
    totalTransfers: transferSuccess + transferFailed
  };
}

Análise Comparativa

Comparar atividade entre usuários:
async function compareUsers(userIds) {
  const userStats = await Promise.all(
    userIds.map(async userId => {
      const response = await fetch(
        `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
        {
          headers: { 'Authorization': `Bearer ${API_KEY}` }
        }
      );
      const data = await response.json();
      return {
        userId,
        totalEvents: data.stats.reduce((sum, s) => sum + s.count, 0),
        stats: data.stats
      };
    })
  );

  // Ordenar por atividade total
  return userStats.sort((a, b) => b.totalEvents - a.totalEvents);
}

Exemplos de Visualização

Preparação de Dados para Gráficos

Preparar dados para gráficos:
async function prepareChartData(userId) {
  const response = await fetch(
    `https://api.gu1.ai/events/user/stats?user_id=${userId}`,
    {
      headers: { 'Authorization': `Bearer ${API_KEY}` }
    }
  );

  const data = await response.json();

  // Para gráfico de pizza
  const pieData = data.stats.map(s => ({
    name: s.event_type,
    value: s.count
  }));

  // Para gráfico de barras
  const barData = data.stats.map(s => ({
    category: s.event_type,
    count: s.count
  }));

  return { pieData, barData };
}

Próximos Passos

Listar Eventos

Consultar eventos individuais

Criar Evento

Rastrear novos eventos

Listar por Entidade

Obter eventos para entidade específica

Análises

Construir dashboards de análise