diff --git a/.env.example b/.env.example index 244443c..1ff19d0 100644 --- a/.env.example +++ b/.env.example @@ -27,3 +27,41 @@ SENTRY_TRACES_SAMPLE_RATE="0.1" # Google Analytics 4 GA4_MEASUREMENT_ID="" GA4_API_SECRET="" + +# Mixpanel Product Analytics +MIXPANEL_TOKEN="" +MIXPANEL_API_SECRET="" +ANALYTICS_ENV="development" + +# ============================================ +# Push Notifications Configuration +# ============================================ + +# Firebase Cloud Messaging (FCM) - Android +FCM_PROJECT_ID="" +FCM_CLIENT_EMAIL="" +FCM_PRIVATE_KEY="" + +# Apple Push Notification Service (APNs) - iOS +APNS_KEY_ID="" +APNS_TEAM_ID="" +APNS_BUNDLE_ID="" +APNS_KEY="" + +# Twilio - SMS (optional) +TWILIO_ACCOUNT_SID="" +TWILIO_AUTH_TOKEN="" +TWILIO_MESSAGING_SERVICE_SID="" + +# Notification Rate Limits +PUSH_RATE_LIMIT=100 +EMAIL_RATE_LIMIT=60 +SMS_RATE_LIMIT=30 +RATE_LIMIT_WINDOW_SECONDS=60 + +# Frontend Environment Variables (Vite) +# Add these to packages/web/.env or your frontend .env files: +# VITE_MIXPANEL_TOKEN= +# VITE_GA_MEASUREMENT_ID= +# VITE_META_PIXEL_ID="" +# VITE_LINKEDIN_PARTNER_ID="" diff --git a/docs/MIXPANEL_ANALYTICS.md b/docs/MIXPANEL_ANALYTICS.md index 58e7dc2..e24c741 100644 --- a/docs/MIXPANEL_ANALYTICS.md +++ b/docs/MIXPANEL_ANALYTICS.md @@ -1,57 +1,149 @@ # ShieldAI Mixpanel Analytics Configuration -## Current Implementation Status +## Implementation Complete ✅ -✅ **Already Implemented:** +The Mixpanel analytics infrastructure is fully implemented and ready for use. This document covers setup and usage. -### Backend (packages/shared-analytics) -- Full MixpanelService with Segment analytics integration -- Event taxonomy defined in `EventType` enum: - - User events: `user_signed_up`, `user_logged_in`, `user_upgraded`, etc. - - Subscription events: `subscription_created`, `subscription_cancelled`, etc. - - Product-specific events: DarkWatch, VoicePrint, SpamShield events -- User identification and group tracking -- KPI definitions (MAU, MRR, conversion rate, churn, etc.) +--- -### Frontend (packages/web) -- Analytics hook (`useAnalytics.ts`) with: - - Mixpanel initialization via `VITE_MIXPANEL_TOKEN` - - Event tracking (`trackEvent`) - - Page view tracking (`trackPageView`) - - Waitlist signup tracking (`trackWaitlistSignup`) -- GA4, Meta Pixel, and LinkedIn Insight integration +## What's Implemented -## Required Actions +### 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 -### 1. Create Mixpanel Project (Manual - Requires Account) -- Sign up for Mixpanel at https://mixpanel.com -- Create project: "ShieldAI" -- Get project token from Project Settings → Project Token +### 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 -### 2. Configure Environment Variables +--- + +## 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 -# Backend (.env) -MIXPANEL_TOKEN= -MIXPANEL_API_SECRET= - -# Frontend (.env) -VITE_MIXPANEL_TOKEN= +# Mixpanel (Backend) +MIXPANEL_TOKEN= +MIXPANEL_API_SECRET= +ANALYTICS_ENV=development # or production, staging ``` -### 3. Event Taxonomy Documentation -See `packages/shared-analytics/src/config/analytics.config.ts` for full event definitions. +### Step 3: Configure Frontend Environment Variables +Create or update `ShieldAI/packages/web/.env`: +```bash +# Mixpanel (Frontend - Vite) +VITE_MIXPANEL_TOKEN= +``` -### 4. User Property Definitions -Standard properties tracked: -- `userId`: User identifier -- `sessionId`: Session identifier -- `platform`: web, mobile, desktop, api -- `version`: App version -- `environment`: development, production, staging +### Step 4: Verify Integration +Backend usage example: +```typescript +import { mixpanelService, EventType } from '@shieldsai/shared-analytics'; -## Integration Points +// Track an event +await mixpanelService.track(EventType.USER_SIGNED_UP, userId, { + plan: 'premium', + referrer: 'google', +}); -- `DarkWatch`: Exposure detection events -- `SpamShield`: Spam detection and blocking events -- `VoicePrint`: Voice enrollment and analysis events -- `Waitlist`: Signup tracking with source attribution +// 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 diff --git a/packages/web/.env.example b/packages/web/.env.example new file mode 100644 index 0000000..bc17a71 --- /dev/null +++ b/packages/web/.env.example @@ -0,0 +1,31 @@ +# ShieldAI Web Application Environment Variables +# Copy this file to .env and fill in the values + +# ============================================ +# Product Analytics +# ============================================ + +# Google Analytics 4 +VITE_GA_MEASUREMENT_ID="" + +# Mixpanel Product Analytics +VITE_MIXPANEL_TOKEN="" + +# Meta (Facebook) Pixel +VITE_META_PIXEL_ID="" + +# LinkedIn Insight Partner ID +VITE_LINKEDIN_PARTNER_ID="" + +# ============================================ +# Application Configuration +# ============================================ + +# API Base URL +VITE_API_BASE_URL=http://localhost:3000 + +# Environment (development, production, staging) +VITE_APP_ENV=development + +# App Version +VITE_APP_VERSION=0.1.0