# ShieldAI Mixpanel Analytics Configuration

## Implementation Complete ✅

The Mixpanel analytics infrastructure is fully implemented and ready for use. This document covers setup and usage.

---

## What's Implemented

### Backend (`packages/shared-analytics`)
- **MixpanelService**: Full implementation using Segment analytics-node SDK
- **Event Taxonomy**: 30+ events defined in `EventType` enum covering:
  - **User Events**: `user_signed_up`, `user_logged_in`, `user_upgraded`, `user_downgraded`
  - **Subscription Events**: `subscription_created`, `subscription_updated`, `subscription_cancelled`, `subscription_renewed`
  - **DarkWatch Events**: `dark_web_scan_started`, `dark_web_scan_completed`, `exposure_detected`, `exposure_resolved`, `watchlist_item_added`, `watchlist_item_removed`
  - **VoicePrint Events**: `voice_enrolled`, `voice_analyzed`, `voice_match_found`, `synthetic_voice_detected`
  - **SpamShield Events**: `call_analyzed`, `sms_analyzed`, `spam_blocked`, `spam_flagged`, `spam_feedback_submitted`
  - **KPI Events**: `mrr_updated`, `conversion_occurred`, `churn_occurred`, `referral_sent`, `referral_converted`
- **User Identification**: `identify()` and `group()` methods for user segmentation
- **KPI Definitions**: MAU, MRR, conversion rate, churn, CAC, LTV, NPS, viral coefficient
- **Data Validation**: Zod schema for event properties

### Frontend (`packages/web/src/hooks/useAnalytics.ts`)
- **Initialization**: Auto-loads Mixpanel script via `initMixpanel()`
- **Event Tracking**: `trackEvent(name, params)` for generic events
- **Page View Tracking**: `trackPageView(path, title)` with automatic page title
- **Waitlist Tracking**: `trackWaitlistSignup(email, source, tier)` with Meta Pixel integration
- **Multi-Platform Support**: GA4, Meta Pixel, LinkedIn Insight included

---

## Setup Instructions

### Step 1: Create Mixpanel Account (Manual)
1. Go to https://mixpanel.com
2. Sign up for an account (free tier: 100K monthly tracked users)
3. Create a new project named "ShieldAI"
4. Copy the **Project Token** from Project Settings → Project Token

### Step 2: Configure Backend Environment Variables
Add to `ShieldAI/.env`:
```bash
# Mixpanel (Backend)
MIXPANEL_TOKEN=<your-mixpanel-project-token>
MIXPANEL_API_SECRET=<optional-api-secret-for-server-side>
ANALYTICS_ENV=development  # or production, staging
```

### Step 3: Configure Frontend Environment Variables
Create or update `ShieldAI/packages/web/.env`:
```bash
# Mixpanel (Frontend - Vite)
VITE_MIXPANEL_TOKEN=<same-project-token-as-backend>
```

### Step 4: Verify Integration
Backend usage example:
```typescript
import { mixpanelService, EventType } from '@shieldsai/shared-analytics';

// Track an event
await mixpanelService.track(EventType.USER_SIGNED_UP, userId, {
  plan: 'premium',
  referrer: 'google',
});

// Identify a user
await mixpanelService.identify(userId, {
  email: 'user@example.com',
  tier: 'premium',
});
```

Frontend usage example:
```typescript
import { trackEvent, trackWaitlistSignup, trackPageView } from './hooks/useAnalytics';

// Track a page view
trackPageView('/waitlist', 'Waitlist Signup');

// Track a signup
trackWaitlistSignup('user@example.com', 'landing_page', 'free');

// Track a custom event
trackEvent('feature_used', { feature: 'darkwatch_scan', duration: 45 });
```

---

## Event Properties Schema

All events support these standard properties (validated via Zod):
- `userId` (string, optional): User identifier
- `sessionId` (string, optional): Session identifier
- `timestamp` (Date, optional): Event timestamp
- `platform` (enum: 'web' | 'mobile' | 'desktop' | 'api', optional): Event source
- `version` (string, optional): App version
- `environment` (string, optional): deployment environment

Additional custom properties are accepted and passed through to Mixpanel.

---

## KPI Definitions

| KPI | Description | Calculation |
|-----|-------------|-------------|
| MAU | Monthly Active Users | COUNT(DISTINCT userId) WHERE timestamp > NOW() - 30 DAYS |
| Paying Users | Active subscriptions | COUNT(DISTINCT userId) WHERE subscription.status = "active" |
| MRR | Monthly Recurring Revenue | SUM(subscription.amount) WHERE subscription.status = "active" |
| Conversion Rate | Free → Paid | COUNT(upgrade events) / COUNT(signup events) |
| Churn Rate | Cancellations | COUNT(cancel events) / COUNT(active subscriptions) |
| CAC | Customer Acquisition Cost | Total marketing spend / COUNT(new paying users) |
| LTV | Lifetime Value | Average subscription amount / Churn rate |
| NPS | Net Promoter Score | % Promoters - % Detractors |
| Viral Coefficient | Referral multiplier | COUNT(referral events) / COUNT(users) |

---

## Alert Thresholds

Configured thresholds for monitoring:
- **Churn**: Warning >5%, Critical >10%
- **Conversion Rate**: Warning <2%, Critical <1%
- **MRR**: Warning <90% target, Critical <80% target
- **NPS**: Warning <50, Critical <40
- **Viral Coefficient**: Warning <0.4, Critical <0.3

---

## Files Modified

- `packages/shared-analytics/src/config/analytics.config.ts` - Event taxonomy & KPIs
- `packages/shared-analytics/src/services/mixpanel.service.ts` - Mixpanel service
- `packages/shared-analytics/src/index.ts` - Exports
- `packages/web/src/hooks/useAnalytics.ts` - Frontend analytics hook
- `.env.example` - Environment variable templates
- `docs/MIXPANEL_ANALYTICS.md` - This documentation

---

## Next Steps

1. **Create Mixpanel account** (requires human action - no API for account creation)
2. **Add tokens to `.env`** files
3. **Test event tracking** in development
4. **Set up Mixpanel dashboards** for KPI monitoring
5. **Configure Mixpanel alerts** for threshold breaches
