# PostHog Analytics Setup Guide for RateRight

## Overview

This guide walks you through setting up PostHog analytics for RateRight. PostHog is a comprehensive product analytics platform that provides event tracking, session recordings, feature flags, and more.

## What is PostHog?

PostHog is an all-in-one product analytics platform that replaces multiple tools:
- **Product Analytics** - Track user behavior and conversion funnels
- **Session Recordings** - Watch how users interact with your app
- **Feature Flags** - Roll out features gradually
- **A/B Testing** - Run experiments to optimize conversion
- **Surveys** - Collect user feedback

## Free Tier Limits

PostHog's generous free tier includes:
- **1M events/month** - More than enough for early-stage startups
- **5K session recordings/month** - Great for understanding user behavior
- **1M feature flag requests/month** - Plenty for gradual rollouts
- **1 project** - Perfect for RateRight's current needs
- **1-year data retention** - Sufficient for trend analysis

## Privacy & GDPR Considerations for Australia

### Key Privacy Features
1. **Data Minimization** - Only collect necessary data
2. **Consent Management** - Implement cookie consent banners
3. **Data Anonymization** - Automatic IP anonymization
4. **Right to be Forgotten** - Easy user data deletion
5. **Data Localization** - PostHog Cloud EU available for stricter requirements

### Australian Privacy Act Compliance
- Ensure your Privacy Policy mentions PostHog analytics
- Implement opt-out mechanisms for users
- Regular data retention reviews (1-year default is good)
- Consider PostHog Cloud EU if handling sensitive data

## Implementation Steps

### Step 1: Sign Up and Project Setup

1. Go to [posthog.com](https://posthog.com) and click "Get started - free"
2. Sign up with your email or GitHub account
3. Create a new project with these settings:
   - **Project name**: "RateRight"
   - **Industry**: "Software"
   - **Company size**: "1-10" (adjust as needed)
   - **Primary use case**: "Product analytics"

### Step 2: Get Your API Keys

After creating your project:
1. Go to Project Settings → Project API Keys
2. Copy your **Project API Key** (starts with `phc_`)
3. Also note your **Instance Address** (usually `https://app.posthog.com`)

### Step 3: Install PostHog

```bash
npm install posthog-js
```

### Step 4: Environment Variables

Add these to your `.env.local` file:

```bash
# PostHog Configuration
NEXT_PUBLIC_POSTHOG_KEY=your_project_api_key_here
NEXT_PUBLIC_POSTHOG_HOST=https://app.posthog.com
```

### Step 5: Create Provider Component

Create `components/posthog-provider.tsx`:

```tsx
'use client'

import posthog from 'posthog-js'
import { PostHogProvider } from 'posthog-js/react'
import { useEffect } from 'react'

export function PostHogProviderWrapper({ children }: { children: React.ReactNode }) {
  useEffect(() => {
    posthog.init(process.env.NEXT_PUBLIC_POSTHOG_KEY!, {
      api_host: process.env.NEXT_PUBLIC_POSTHOG_HOST || 'https://app.posthog.com',
      person_profiles: 'identified_only', // Only create profiles for identified users
      capture_pageview: false, // We'll capture manually for better control
      capture_pageleave: true, // Capture time on page
      autocapture: {
        // Configure what to autocapture
        dom_event_allowlist: ['click', 'submit'],
        element_allowlist: ['button', 'a', 'form'],
        css_selector_allowlist: ['[data-ph-capture]'],
      },
      // Privacy settings
      mask_all_text: false,
      mask_all_element_attributes: false,
      enable_recording_console_log: true,
      // Session recording config
      session_recording: {
        maskAllInputs: true,
        maskTextSelector: '[data-ph-mask]',
        blockClass: 'ph-no-capture',
      },
      // GDPR compliance
      persistence: 'localStorage+cookie',
      persistence_name: 'ph_rateRight',
      cookie_name: 'ph_rateRight',
      cross_subdomain_cookie: false,
      secure_cookie: true,
      // Performance
      request_batching: true,
      batch_size: 20,
      flush_interval: 30000,
    })
  }, [])

  return <PostHogProvider client={posthog}>{children}</PostHogProvider>
}
```

### Step 6: Update Root Layout

In `app/layout.tsx`, wrap your app with the provider:

```tsx
import { PostHogProviderWrapper } from '@/components/posthog-provider'

export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>
        <PostHogProviderWrapper>
          {children}
        </PostHogProviderWrapper>
      </body>
    </html>
  )
}
```

### Step 7: Create PostHog Client Wrapper

Create `lib/posthog.ts`:

```typescript
import posthog from 'posthog-js'

// Export posthog instance for use throughout the app
export { posthog }

// Helper function to identify users
export const identifyUser = (userId: string, properties?: Record<string, any>) => {
  posthog.identify(userId, properties)
}

// Helper function to capture custom events
export const captureEvent = (eventName: string, properties?: Record<string, any>) => {
  posthog.capture(eventName, properties)
}

// Helper function to reset user data (for logout)
export const resetPostHog = () => {
  posthog.reset()
}

// Helper function to set user properties
export const setUserProperties = (properties: Record<string, any>) => {
  posthog.people.set(properties)
}

// Helper function to alias anonymous user to identified user
export const aliasUser = (distinctId: string) => {
  posthog.alias(distinctId)
}

// Page view tracking
export const capturePageView = (pageName?: string, properties?: Record<string, any>) => {
  posthog.capture('$pageview', {
    page: pageName || window.location.pathname,
    ...properties
  })
}

// Revenue tracking
export const captureRevenue = (amount: number, properties?: Record<string, any>) => {
  posthog.capture('$transaction', {
    $amount: amount,
    ...properties
  })
}
```

## Key Events to Track

### User Journey Events

1. **User Registration**
```typescript
import { captureEvent, identifyUser } from '@/lib/posthog'

// After successful signup
identifyUser(user.id, {
  email: user.email,
  name: user.name,
  userType: user.userType, // 'contractor' or 'homeowner'
  signupDate: new Date().toISOString()
})

captureEvent('user_signup_completed', {
  userType: user.userType,
  signupMethod: 'email', // or 'google', 'facebook'
  referralSource: document.referrer || 'direct'
})
```

2. **Profile Completion**
```typescript
// After profile completion
captureEvent('profile_completed', {
  userType: user.userType,
  completionPercentage: 100,
  fieldsCompleted: ['name', 'email', 'phone', 'location', 'skills']
})
```

3. **Job Posting (Homeowners)**
```typescript
// When a job is posted
captureEvent('job_posted', {
  jobId: job.id,
  category: job.category,
  budgetRange: job.budgetRange,
  location: job.location,
  urgency: job.urgency,
  expectedQuotes: job.expectedQuotes
})
```

4. **Quote Submission (Contractors)**
```typescript
// When a contractor submits a quote
captureEvent('quote_submitted', {
  jobId: quote.jobId,
  contractorId: quote.contractorId,
  quoteAmount: quote.amount,
  estimatedDuration: quote.estimatedDuration,
  materialsIncluded: quote.materialsIncluded
})
```

5. **Hire Event**
```typescript
// When a homeowner hires a contractor
captureEvent('contractor_hired', {
  jobId: job.id,
  contractorId: contractor.id,
  homeownerId: homeowner.id,
  quoteAmount: acceptedQuote.amount,
  jobCategory: job.category
})
```

6. **Payment Events**
```typescript
import { captureRevenue } from '@/lib/posthog'

// When payment is processed
captureRevenue(payment.amount, {
  jobId: payment.jobId,
  paymentMethod: payment.method,
  paymentType: payment.type, // 'deposit', 'milestone', 'final'
  contractorId: payment.contractorId
})
```

### Engagement Events

7. **Search/Filter Usage**
```typescript
// Track search queries
captureEvent('job_search_performed', {
  query: searchQuery,
  filters: {
    category: selectedCategory,
    location: selectedLocation,
    budget: budgetRange
  },
  resultsCount: results.length
})
```

8. **Feature Usage**
```typescript
// Track specific feature usage
captureEvent('feature_used', {
  feature: 'saved_contractors',
  action: 'added_to_list'
})
```

## Session Recording Configuration

### When to Record Sessions

Configure session recordings to capture:
- New user onboarding flows
- Job posting process
- Quote submission process
- Payment flows
- Error states or confusing UI

### Privacy-Safe Recording Settings

In your PostHog provider configuration:

```tsx
session_recording: {
  maskAllInputs: true, // Mask all form inputs
  maskTextSelector: '[data-ph-mask]', // Mask specific elements
  blockClass: 'ph-no-capture', // Block elements with this class
  // Additional privacy settings
  maskTextFn: (text) => {
    // Custom masking function for sensitive data
    if (text.includes('@')) return '[EMAIL]'
    if (text.match(/\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}/)) return '[CARD]'
    return text
  }
}
```

### Mark Sensitive Elements

In your components, mark sensitive elements:

```tsx
// Mask this element in recordings
<div data-ph-mask>
  Sensitive information here
</div>

// Completely block this element
<div className="ph-no-capture">
  Never record this
</div>

// Allow specific tracking
<button data-ph-capture="true">
  Track this click
</button>
```

## Example Usage in Key Pages

### 1. Homepage Tracking

```tsx
'use client'

import { useEffect } from 'react'
import { capturePageView } from '@/lib/posthog'

export default function HomePage() {
  useEffect(() => {
    capturePageView('homepage', {
      landingSection: 'hero',
      utm_source: searchParams.get('utm_source'),
      utm_campaign: searchParams.get('utm_campaign')
    })
  }, [])

  return (
    <div>
      {/* Your homepage content */}
    </div>
  )
}
```

### 2. Job Posting Form

```tsx
'use client'

import { captureEvent } from '@/lib/posthog'

export default function JobPostingForm() {
  const handleSubmit = async (formData) => {
    try {
      const job = await createJob(formData)
      
      captureEvent('job_posted', {
        jobId: job.id,
        category: formData.category,
        hasBudget: !!formData.budget,
        hasDeadline: !!formData.deadline,
        descriptionLength: formData.description.length
      })
    } catch (error) {
      captureEvent('job_post_failed', {
        error: error.message,
        step: 'validation'
      })
    }
  }

  return (
    <form onSubmit={handleSubmit}>
      {/* Form fields */}
    </form>
  )
}
```

### 3. User Dashboard

```tsx
'use client'

import { useEffect } from 'react'
import { captureEvent, setUserProperties } from '@/lib/posthog'

export default function Dashboard({ user }) {
  useEffect(() => {
    // Set user properties for better segmentation
    setUserProperties({
      lastActiveDate: new Date().toISOString(),
      dashboardViews: (user.dashboardViews || 0) + 1,
      hasActiveJobs: user.activeJobs > 0,
      hasCompletedJobs: user.completedJobs > 0
    })
  }, [user])

  const handleJobClick = (job) => {
    captureEvent('dashboard_job_clicked', {
      jobId: job.id,
      jobStatus: job.status,
      jobAge: Date.now() - new Date(job.createdAt).getTime()
    })
  }

  return (
    <div>
      {/* Dashboard content */}
    </div>
  )
}
```

## Testing Your Implementation

### 1. Local Development Testing

Add this test component to verify PostHog is working:

```tsx
'use client'

import { usePostHog } from 'posthog-js/react'
import { useEffect } from 'react'

export function PostHogTest() {
  const posthog = usePostHog()

  useEffect(() => {
    console.log('PostHog initialized:', posthog)
    
    // Test event
    posthog.capture('test_event', {
      test: true,
      timestamp: new Date().toISOString()
    })
  }, [posthog])

  return (
    <div className="fixed bottom-4 right-4 bg-green-100 p-4 rounded shadow">
      <p className="text-sm font-semibold">PostHog Status: Connected</p>
      <button 
        onClick={() => posthog.capture('manual_test')}
        className="mt-2 px-3 py-1 bg-green-500 text-white rounded text-xs"
      >
        Test Event
      </button>
    </div>
  )
}
```

### 2. Production Checklist

Before deploying:
- [ ] Remove test components
- [ ] Verify all environment variables are set
- [ ] Check session recording settings are privacy-compliant
- [ ] Test key conversion events
- [ ] Verify GDPR consent implementation
- [ ] Set up billing alerts in PostHog dashboard

## Advanced Configuration

### Feature Flags Setup

```tsx
import { useFeatureFlagEnabled } from 'posthog-js/react'

export function NewFeature() {
  const showNewFeature = useFeatureFlagEnabled('new-feature-flag')

  if (!showNewFeature) {
    return <OldFeature />
  }

  return <NewFeatureComponent />
}
```

### A/B Testing

```tsx
import { useFeatureFlagVariantKey } from 'posthog-js/react'

export function PricingPage() {
  const variant = useFeatureFlagVariantKey('pricing-page-test')

  if (variant === 'test') {
    return <PricingPageVariant />
  }

  return <PricingPageControl />
}
```

## What Michael Needs to Do

1. **Sign up at posthog.com**
   - Create account with business email
   - Set up "RateRight" project
   - Copy Project API Key from settings

2. **Add Environment Variables**
   - Add `NEXT_PUBLIC_POSTHOG_KEY` to Vercel/Railway
   - Add `NEXT_PUBLIC_POSTHOG_HOST` (usually https://app.posthog.com)

3. **Deploy the Code**
   - Copy all the code files to your project
   - Ensure PostHog provider wraps your app
   - Test events are firing correctly

4. **Configure in PostHog Dashboard**
   - Set up custom events (user_signup_completed, job_posted, etc.)
   - Configure session recording rules
   - Set up any feature flags for gradual rollouts
   - Invite team members if needed

5. **Monitor and Optimize**
   - Check events are being captured correctly
   - Review session recordings for user insights
   - Set up conversion funnels for key flows
   - Configure alerts for important metrics

## Support and Resources

- **PostHog Documentation**: https://posthog.com/docs
- **Next.js Integration Guide**: https://posthog.com/docs/libraries/next-js
- **Privacy Documentation**: https://posthog.com/docs/privacy
- **Community Support**: https://posthog.com/questions

## Next Steps

After basic setup, consider:
1. Setting up conversion funnels for signup → job posting
2. Creating cohorts for different user types
3. Implementing feature flags for new features
4. Setting up A/B tests for key pages
5. Creating dashboards for key metrics

---

*This guide was created for RateRight's PostHog implementation. Update events and properties based on your specific business needs.*