# Analytics Integration Guide

## Overview

This guide covers how to integrate analytics event tracking across all Lilith services to power business KPI calculations.

## Service Integration

### Event Ingestion Client

```javascript
const { AnalyticsClient } = require('@lilith/lib');

class ServiceAnalytics {
  constructor(serviceName) {
    this.analytics = new AnalyticsClient({
      baseUrl: process.env.OBSERVABILITY_URL,
      serviceName,
      environment: process.env.ENVIRONMENT
    });
  }

  async trackUserSession(userId, sessionId, platform) {
    await this.analytics.track({
      event_type: 'session.started',
      user_hash: this.hashUserId(userId),
      session_id: sessionId,
      context: {
        platform,
        service: this.serviceName
      },
      consent: true
    });
  }

  async trackSignupCompletion(userId, signupMethod) {
    await this.analytics.track({
      event_type: 'signup.completed',
      user_hash: this.hashUserId(userId),
      context: {
        signup_method: signupMethod,
        conversion_path: 'direct'
      },
      consent: true
    });
  }

  hashUserId(userId) {
    return crypto.createHash('sha256')
      .update(`${userId}:${process.env.USER_SALT}`)
      .digest('hex');
  }
}
```

### Authentication Service Integration

```javascript
// services/auth/src/analytics-integration.js
const ServiceAnalytics = require('./service-analytics');
const analytics = new ServiceAnalytics('auth-service');

// Track successful signups
app.post('/v1/auth/signup', async (request, reply) => {
  try {
    const user = await createUser(request.body);

    // Track signup completion
    await analytics.trackSignupCompletion(user.id, 'email_password');

    reply.send({ user_id: user.id, status: 'created' });
  } catch (error) {
    reply.status(400).send({ error: error.message });
  }
});

// Track session starts
app.post('/v1/auth/session', async (request, reply) => {
  try {
    const session = await createSession(request.body);

    // Track session start
    await analytics.trackUserSession(
      session.user_id,
      session.id,
      request.headers['x-platform'] || 'web'
    );

    reply.send({ session });
  } catch (error) {
    reply.status(400).send({ error: error.message });
  }
});
```

### Conversation Service Integration

```javascript
// services/conversation/src/analytics-integration.js
const analytics = new ServiceAnalytics('conversation-service');

// Track chat engagement
app.post('/v1/conversations/messages', async (request, reply) => {
  try {
    const message = await createMessage(request.body);

    // Track chat message sent
    await analytics.track({
      event_type: 'chat.message_sent',
      user_hash: analytics.hashUserId(request.user.id),
      session_id: request.session.id,
      context: {
        message_type: message.type,
        persona: message.persona,
        length: message.content.length
      },
      consent: request.user.analytics_consent
    });

    reply.send({ message });
  } catch (error) {
    reply.status(500).send({ error: error.message });
  }
});
```

## Data Pipeline Architecture

### Event Flow

```
Service APIs → Analytics Client → Observability Service → KPI Calculator → Dashboard API
     ↓              ↓                    ↓                    ↓              ↓
   Events      Validation        Event Storage         Aggregation    Real-time KPIs
```

### Real-time Processing

```javascript
// KPI calculation pipeline
class KPICalculator {
  constructor() {
    this.eventStream = new EventStream();
    this.kpiCache = new Map();
    this.calculations = new Map();
  }

  async startCalculations() {
    // Real-time DAU calculation
    this.eventStream.on('session.started', async (event) => {
      await this.updateDAU(event);
    });

    // Real-time conversion tracking
    this.eventStream.on('signup.completed', async (event) => {
      await this.updateConversionRate(event);
    });

    // Batch calculations every 5 minutes
    setInterval(() => {
      this.calculateBatchKPIs();
    }, 5 * 60 * 1000);
  }

  async updateDAU(event) {
    const today = new Date().toISOString().split('T')[0];
    const cacheKey = `dau:${today}`;

    let dau = this.kpiCache.get(cacheKey) || new Set();
    dau.add(event.user_hash || event.session_id);
    this.kpiCache.set(cacheKey, dau);

    // Update dashboard if significant change
    if (dau.size % 100 === 0) {
      await this.publishKPIUpdate('dau', dau.size);
    }
  }
}
```

## Data Quality & Validation

### Event Validation

```javascript
const validateAnalyticsEvent = (event) => {
  // Required fields
  if (!event.event_type || !event.session_id) {
    throw new Error('Missing required fields');
  }

  // Valid event types
  const validEventTypes = [
    'session.started', 'session.ended',
    'signup.started', 'signup.completed',
    'chat.message_sent', 'voice.session_started',
    'meditation.started', 'meditation.completed',
    'payment.started', 'payment.completed'
  ];

  if (!validEventTypes.includes(event.event_type)) {
    throw new Error(`Invalid event type: ${event.event_type}`);
  }

  // User identity validation
  if (event.user_hash && !/^[a-f0-9]{64}$/.test(event.user_hash)) {
    throw new Error('Invalid user_hash format');
  }

  // Timestamp validation
  if (event.timestamp && !moment(event.timestamp).isValid()) {
    throw new Error('Invalid timestamp format');
  }

  // Consent requirement
  if (event.consent !== true) {
    throw new Error('User consent required for analytics');
  }

  return true;
};
```

### Data Deduplication

```javascript
const deduplicateEvents = (events) => {
  const seen = new Set();
  const deduped = [];

  for (const event of events) {
    const key = `${event.event_type}:${event.user_hash}:${event.session_id}:${Math.floor(new Date(event.timestamp).getTime() / 300000)}`;

    if (!seen.has(key)) {
      seen.add(key);
      deduped.push(event);
    }
  }

  return deduped;
};
```

## Testing & Validation

### Automated KPI Testing

```bash
# Test business metrics endpoints
npm test -- tests/observability.business-metrics.spec.js

# Test KPI calculation accuracy
npm test -- tests/observability.business-kpis-wiring.spec.js

# Validate analytics event ingestion
npm test -- tests/analytics-event-validation.spec.js
```

### Manual Testing

```bash
# Test dashboard endpoint
curl "$OBSERVABILITY_URL/v1/metrics/dashboards/business"

# Test report generation
curl "$OBSERVABILITY_URL/v1/metrics/reports/business?period=7d"

# Test analytics event ingestion
curl -X POST "$OBSERVABILITY_URL/v1/analytics/events" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $TOKEN" \
  -d '{
    "event_type": "session.started",
    "user_hash": "test_user_hash",
    "session_id": "test_session_123",
    "consent": true
  }'
```

---
*Generated automatically by business-metrics-docs-generator.js*
*Last updated: 2025-09-26T09:29:19.731Z*
