# Affiliate System Testing Guide

**Last Updated:** 2026-01-30

Comprehensive testing guide for the affiliate partner system after optimization and modularization.

## Testing Checklist

### API Testing

**Test Script:** `v2/scripts/test-affiliate-apis.php` (to be created)

**Endpoints to Test:**

1. **Dashboard Data API** (`/v2/api/affiliate-dashboard-data.php`)
   - [ ] Returns valid JSON
   - [ ] Contains required fields (partner, kpis, lead_counts, mrr, etc.)
   - [ ] Data matches cached HubSpot data
   - [ ] Error handling works (401, 404, 500)

2. **Leads API** (`/v2/api/affiliate-leads.php`)
   - [ ] Returns formatted leads array
   - [ ] Lead status determination is correct
   - [ ] Sorting by date works
   - [ ] Empty state handled gracefully

3. **Earnings API** (`/v2/api/affiliate-earnings.php`)
   - [ ] MRR calculations are correct
   - [ ] Deal formatting includes partner MRR
   - [ ] Top deals sorted correctly
   - [ ] Status breakdown percentages are accurate

4. **Leaderboard API** (`/v2/api/affiliate-leaderboard.php`)
   - [ ] Returns top N partners
   - [ ] Anonymous mode works (if enabled)
   - [ ] Sorting by MRR is correct

5. **Levels API** (`/v2/api/affiliate-levels.php`)
   - [ ] Level calculation is correct
   - [ ] Badge calculation works
   - [ ] Progress to next level is accurate
   - [ ] Leaderboard rank is correct

**Test Commands:**

```bash
# Test all APIs (requires authenticated session)
php v2/scripts/test-affiliate-apis.php

# Test individual endpoint
curl -b cookies.txt http://localhost:8003/v2/api/affiliate-dashboard-data.php
```

### Visual Testing

**Pages to Test:**

1. **Dashboard** (`/partner/dashboard`)
   - [ ] KPI cards display correctly
   - [ ] Charts render properly (MRR trend, conversion funnel, MRR status, lead trend)
   - [ ] Recent activity section works
   - [ ] Responsive design (mobile, tablet, desktop)
   - [ ] Loading states display correctly
   - [ ] Empty states display correctly

2. **Leads** (`/partner/leads`)
   - [ ] Table displays all leads
   - [ ] Filter tabs work (all, new, qualified, deal, won)
   - [ ] Status badges display correctly
   - [ ] Date formatting is correct
   - [ ] Responsive table layout

3. **Earnings** (`/partner/earnings`)
   - [ ] Earnings summary cards display correctly
   - [ ] Charts render (MRR status, deal status, MRR trend, top deals)
   - [ ] Deals table displays correctly
   - [ ] Status badges for deals work
   - [ ] Currency formatting is correct

4. **Levels** (`/partner/levels`)
   - [ ] Level hero displays current level
   - [ ] Progress bar shows correct progress
   - [ ] Level stepper displays all levels
   - [ ] Badge grid displays correctly
   - [ ] Achievements section works
   - [ ] Next steps are relevant

5. **Leaderboard** (`/partner/leaderboard`)
   - [ ] Top partners display correctly
   - [ ] Anonymous mode works (if enabled)
   - [ ] Ranking is correct

6. **Referral URLs** (`/partner/referral-urls`)
   - [ ] URL generation works
   - [ ] Copy to clipboard works
   - [ ] UTM parameters are preserved

7. **Settings** (`/partner/settings`)
   - [ ] Profile update works
   - [ ] Password change works
   - [ ] Form validation works

**Visual Regression Checklist:**

- [ ] No CSS conflicts (check browser console)
- [ ] Sidebar navigation works on all pages
- [ ] Active nav item highlighting is correct
- [ ] Buttons and links are clickable
- [ ] Forms submit correctly
- [ ] Error messages display correctly
- [ ] Success messages display correctly

### Performance Testing

**Before Optimization Baseline:**

Run PageSpeed Insights on all partner pages and record:
- LCP (Largest Contentful Paint)
- FID (First Input Delay)
- CLS (Cumulative Layout Shift)
- Total page size
- Number of requests

**After Optimization:**

Run PageSpeed Insights again and compare:
- [ ] LCP improved (target: < 2.5s)
- [ ] FID improved (target: < 100ms)
- [ ] CLS improved (target: < 0.1)
- [ ] Page size reduced (due to shared CSS/JS)
- [ ] Number of requests reduced

**Test Commands:**

```bash
# Run PageSpeed Insights API (requires API key)
# Or use browser extension: https://chrome.google.com/webstore/detail/pagespeed-insights

# Check file sizes
ls -lh v2/css/affiliate-*.css
ls -lh v2/js/affiliate-*.js

# Check minified files exist
ls -lh v2/css/affiliate-*.min.css
ls -lh v2/js/affiliate-*.min.js
```

### Functional Testing

**Shared Components:**

1. **API Base Helper**
   - [ ] `requireAffiliateAuthAPI()` returns partner ID
   - [ ] `loadCachedHubSpotData()` loads cache correctly
   - [ ] `sendJSONResponse()` formats JSON correctly
   - [ ] `handleAPIError()` logs and sends error response

2. **Data Formatters**
   - [ ] `formatLeadForAPI()` determines status correctly
   - [ ] `formatDealForAPI()` calculates MRR correctly
   - [ ] `calculateLeadCounts()` counts correctly
   - [ ] `formatMRRStatusBreakdown()` calculates percentages correctly

3. **JavaScript Utilities**
   - [ ] `escapeHtml()` prevents XSS
   - [ ] `formatCurrency()` formats EUR correctly
   - [ ] `formatDate()` formats dates in German locale
   - [ ] `handleAPIError()` displays error UI
   - [ ] `showLoadingState()` displays loading UI
   - [ ] `showEmptyState()` displays empty UI

4. **Chart Factories**
   - [ ] `createMRRLineChart()` creates line chart
   - [ ] `createMRRDonutChart()` creates donut chart
   - [ ] `createBarChart()` creates bar chart
   - [ ] Charts are responsive
   - [ ] Charts handle empty data gracefully

### Browser Compatibility

Test on:
- [ ] Chrome (latest)
- [ ] Firefox (latest)
- [ ] Safari (latest)
- [ ] Edge (latest)
- [ ] Mobile Safari (iOS)
- [ ] Chrome Mobile (Android)

### Accessibility Testing

- [ ] Keyboard navigation works
- [ ] Screen reader compatibility (test with VoiceOver/NVDA)
- [ ] Color contrast meets WCAG AA standards
- [ ] Focus indicators are visible
- [ ] Form labels are associated correctly

## Test Scripts

### API Test Script

Create `v2/scripts/test-affiliate-apis.php`:

```php
<?php
/**
 * Test Affiliate APIs
 * 
 * Tests all affiliate API endpoints after refactoring.
 */

require_once __DIR__ . '/../../config/affiliate-config.php';
require_once __DIR__ . '/../../includes/affiliate-auth.php';

// Test authentication
session_start();
requireAffiliateAuth();

$partner = getAuthenticatedPartner();
if (!$partner) {
    die("Not authenticated. Please log in first.\n");
}

echo "Testing Affiliate APIs for partner: {$partner['partner_id']}\n\n";

$endpoints = [
    'Dashboard' => '/v2/api/affiliate-dashboard-data.php',
    'Leads' => '/v2/api/affiliate-leads.php',
    'Earnings' => '/v2/api/affiliate-earnings.php',
    'Leaderboard' => '/v2/api/affiliate-leaderboard.php',
    'Levels' => '/v2/api/affiliate-levels.php'
];

foreach ($endpoints as $name => $endpoint) {
    echo "Testing {$name} API...\n";
    
    $ch = curl_init('http://localhost:8003' . $endpoint);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_COOKIE, session_name() . '=' . session_id());
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    $data = json_decode($response, true);
    
    if ($httpCode === 200 && isset($data['success']) && $data['success']) {
        echo "  ✓ Success\n";
        echo "  Response keys: " . implode(', ', array_keys($data['data'] ?? [])) . "\n";
    } else {
        echo "  ✗ Failed (HTTP {$httpCode})\n";
        echo "  Error: " . ($data['error'] ?? 'Unknown error') . "\n";
    }
    echo "\n";
}

echo "Testing complete.\n";
```

## Regression Testing

After optimization, verify:

- [ ] All existing functionality still works
- [ ] No data loss or corruption
- [ ] Performance is equal or better
- [ ] Visual appearance is unchanged (except improvements)
- [ ] Error handling still works
- [ ] Authentication still works
- [ ] HubSpot sync still works

## Automated Testing (Future)

Consider adding:
- PHPUnit tests for API endpoints
- Jest tests for JavaScript utilities
- Visual regression tests (Percy, Chromatic)
- E2E tests (Playwright, Cypress)

## Related Documentation

- [Architecture](ARCHITECTURE.md) - System architecture
- [API Reference](API_REFERENCE.md) - API endpoint documentation
- [Dashboard Guide](DASHBOARD_GUIDE.md) - Dashboard usage guide
